T-SQL Error In Creating A Stored Procedure That Has Three Parameters: Incorrect Syntax Near 'WHERE'

Feb 17, 2008

Hi all,

I copied the the following code from a book to the query editor of my SQL Server Management Studio Express (SSMSE):
///--MuCh14spInvTotal3.sql--///
USE AP --AP Database is installed in the SSMSE--
GO
CREATE PROC spInvTotal3
@InvTotal money OUTPUT,
@DateVar smalldatetime = NULL,
@VendorVar varchar(40) = '%'
AS

IF @DateVar IS NULL
SELECT @DateVar = MIN(InvoiceDate)

SELECT @InvTotal = SUM(InvoiceTotal)
FROM Invoices JOIN Vendors
WHERE (InvoiceDate >= @DateVar) AND
(VendorName LIKE @VendorVar)
GO
///////////////////////////////////////////////////////////////
Then I executed it and I got the following error:
Msg 156, Level 15, State 1, Procedure spInvTotal3, Line 12
Incorrect syntax near the keyword 'WHERE'.
I do not know what wrong with it and how to correct this problem.

Please help and advise.

Thanks,
Scott Chang

View 18 Replies


ADVERTISEMENT

Receiving Error 156 - Incorrect Syntax When Compiling Stored Procedure

May 14, 2008

The following query works fine in query analyzer, but when I add it to my stored procedure I receive an error 156. How do I work around this?

select distinct(dateposted)
from billingprocedures bp1,
billingprocedureordercomponentvalues bpocv,
ordercomponentvalues ocv
where bp1.billingid = @billingid
and bp1.procedureid = bpocv.billingprocedureid
and bpocv.ordercomponentvalueid = ocv.ordercomponentvalueid

Thanks,
Bryan

View 12 Replies View Related

Creating A Table Through Stored Procedure Shows An Syntax Error

May 26, 2000

hai guys,
i have written a stored procedure which creates a table ex:
USE PUBS
GO
IF EXISTS (SELECT * FROM SYSOBJECTS WHERE NAME = 'RC_STRPROC')
DROP PROCEDURE RC_STRPROC
GO
USE PUBS
GO
CREATE PROCEDURE RC_STRPROC
(@TBLNAME VARCHAR(35), @COLVAL1 VARCHAR(35), @COLVAL2 VARCHAR(35))
AS
IF EXISTS (SELECT * FROM SYSOBJECTS WHERE NAME = '@TBLNAME')
DROP TABLE @TBLNAME
CREATE TABLE @TBLNAME
(@COLVAL1, @COLVAL2)
GO
it gives an syntax error at '@tblname'
can u guys tell me the problem

thanks
hiss

View 2 Replies View Related

Error Creating Table - Incorrect Syntax

May 27, 2014

Have been given this code to create a table

CREATE TABLE 'emaillist' (
'id' INT(11) NOT NULL AUTO_INCREMENT,
'clientname' VARCHAR(200) NOT NULL DEFAULT '0',
'email' VARCHAR(200) NOT NULL DEFAULT '0',
PRIMARY KEY ('id')
);

when I execute it says

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'emaillist'.

What the correct code should be?

View 3 Replies View Related

Incorrect Syntax Near '?' When Trying To Use Parameters

Feb 23, 2007

I must be missing something simple.  I have the following code that is not too complicated.  I am trying to read a session variable (referenced in the <selectparameters> section) and use it to filter my SELECT statement.  The select statement runs fine and displays everything in the gridview control until I put the "WHERE PackagingItemNo = ?" clause in.  Then I get the error message in the title.  I've tried using quotes, brackets, etc. to see if there's some syntax issue I'm missing here but I'm lost.  I see numerous code examples that look identical to mine.  What am I missing?

I'm mostly an Oracle and PL/SQL type so I'm a little lost here...

 

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BorderColor="Black"

AllowPaging="true" DataKeyNames="InBoundID" BorderStyle="Solid" BorderWidth="1px"

Width="100%" AllowSorting="True" DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display.">

<HeaderStyle HorizontalAlign="Left" />

<Columns>

<asp:BoundField DataField="PackagingItemNo" HeaderText="Pack.Item#" SortExpression="PackagingItemNo" />

<asp:BoundField DataField="QuantityShipped" HeaderText="L" SortExpression="QuantityShipped" />

</Columns>

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDBConnectionString1 %>"

ProviderName="<%$ ConnectionStrings:MyDBConnectionString1.ProviderName %>"

SelectCommand="SELECT [InBoundID], [ShipID], [ShipItemID], [LocationID], [ArtisanShipNo], [ArrivalDate], [ArrivalTime], [ShipMode], [PackagingItemNo], [QuantityIn], [QuantityShipped], [QuantityClaimed], [ContainerType], [UnloadInvoicedYN], [CarrierName], [BillOfLading], [ShippingPointName], [ShippingPointState], [ReleaseNumber], [ProfileFlag], [TagFlag], [ActiveYN], [WHouseUserID], [UpdatedOn], [UpdateIs] FROM [WHouseInBound] WHERE PackagingItemNo = ?">

<SelectParameters>

<asp:SessionParameter Name="PackItemNo" SessionField="PackagingItemNo" DefaultValue="12345" />

</SelectParameters>

</asp:SqlDataSource>

View 3 Replies View Related

Incorrect Syntax Near 'XML'-While Creating XML Schema

Jul 3, 2007

 Hi,       Im trying to create a xml schema like     CREATE XML SCHEMA COLLECTION BooksSchemaCollection ASN'<?xml version="1.0" encoding="UTF-16"?><xsd:schema elementFormDefault="unqualified"   attributeFormDefault="unqualified"   xmlns:xsd="http://www.w3.org/2001/XMLSchema" >    <xsd:element name="book">        <xsd:complexType mixed="false">            <xsd:sequence>                <xsd:element name="name" type="xsd:string"/>                <xsd:element name="author" type="xsd:string"/>                <xsd:element name="publisher" type="xsd:string"/>                <xsd:element name="cost" type="xsd:integer"/>                <xsd:element name="comments" type="xsd:string"/>            </xsd:sequence>                              </xsd:complexType>    </xsd:element></xsd:schema>';  

But when i execute , im getting a error  like Incorrect syntax near 'XML' .any one know why its comming?????? Thanks 

View 1 Replies View Related

Creating A Stored Procedure With Parameters And Multiple Sql-server Queries

Jan 23, 2008

I need to create a stored procedure that will have about 10-15 queries and take 3 parameters.
 the variables will be: @lastmonth, @curryear and @id
@lastmonth should inherit Session variable intlastmonth
@curryear should inherit Session variable intCurrYear
@id should inherit Session id
 One example query is SELECT hours FROM table WHERE MONTH ='" + Session("intLastmonth") + "'  AND YEAR ='" + Session("intCurrYear") + "' AND [NUMBER] = '" + Session("id")
The rest of the queries will be similar and use all 3 variables as well.
How can I go about this and how will queries be seperated.
 

View 2 Replies View Related

Creating Stored Procedure With Temp Table - Pass 6 Parameters

Sep 9, 2014

I need to create a Stored Procedure in SQL server which passes 6 input parameters Eg:

ALTER procedure [dbo].[sp_extract_Missing_Price]
@DisplayStart datetime,
@yearStart datetime,
@quarterStart datetime,
@monthStart datetime,
@index int
as

Once I declare the attributes I need to create a Temp table and update the data in it. Creating temp table

Once I have created the Temp table following query I need to run

SELECT date FROM #tempTable
WHERE #temp.date NOT IN (SELECT date FROM mytable WHERE mytable.date IN (list-of-input-attributes) and index = @index)

The above query might return null result or a date .

In case null return output as "DataNotMissing"
In case not null return date and string as "Datamissing"

View 3 Replies View Related

Correct Syntax For Parameters When Creating SQL Job

Dec 30, 2007

I'm trying to create a SQL job in SQL Server and am a little unclear about the formatting.Here's a snippet from the stored procedure that creates the job:CREATE PROCEDURE [dbo].[spArchive]     @DB            varchar(30),    @Date        DateTimeAS EXEC msdb.dbo.sp_add_jobstep @job_name = 'ArchiveIncentives'     , @step_id = 1    , @step_name = 'ArchiveAHD'    , @subsystem = 'TSQL'    , @command = 'spArchiveAHD ''@Date'''    , @on_success_action = 3     , @on_fail_action = 2     , @database_name = '@DB'     , @retry_attempts = 1   In this case, the job will be calling this stored procedure:CREATE PROCEDURE [dbo].[spArchiveAHD] (    @dtArchiveBefore DateTime)AS I'm unclear about these lines:    @command = 'spArchiveAHD ''@Date'''    @database_name = '@DB'   Do they look correct to you or should I drop some/all of the apostrophes?Robert W. 

View 5 Replies View Related

ERROR:Syntax Error Converting Datetime From Character String. With Stored Procedure

Jul 12, 2007

Hi All,





i have migrated a DTS package wherein it consists of SQL task.

this has been migrated succesfully. but when i execute the package, i am getting the error with Excute SQL task which consists of Store Procedure excution.



But the SP can executed in the client server. can any body help in this regard.





Thanks in advance,

Anand

View 4 Replies View Related

Alias &#043; Stored Procedure Syntax Error

Jun 21, 2008

Hi,

Im new to this forum and new also to SQL SERVER Edition Express.

Im trying to creat stored procedure. My main problem is that I need to display an alias consisting of 2 fields in a combobox (VB.Net) using also an innerjoin. Can anyone help me find my mistake please


My code is here and the error is :
-----------------------------------------------------------
Msg 156, Level 15, State 1, Procedure LA_suppName, Line 16
Incorrect syntax near the keyword 'INNER'.

-----------------------------------------------------------

@supplierFID int,
@supplierID int,
@LANo nvarchar(15) OUTPUT,
@suppName nvarchar(MAX) OUTPUT

AS

BEGIN
SET NOCOUNT ON;

-- Insert statements for procedure here

SELECT tb_LA.LANo, tb_supplier.suppName AS OrderSupplier
INNER JOIN tb_supplier ON tb_LA.supplierFID=tb_supplier.supplierID
Order by tb_LA.LANo

END

------------------------------------------------------

Eventually I would need to use tb_LA.LANo and make a query to populate the tb_LABooks in another combobox on selectvaluechanged. Is this possible please???


Many thanks

View 5 Replies View Related

Incorrect Syntax Error

Sep 17, 2007

I am getting an error saying, "Incorrect syntax near keyword 'ON'" Could someone please help? Here is my code: 
str = "SELECT FAC_REQUEST.*, StateFAC.*, STATUS.sStatus, FAC_TYPE.Facility_Type FROM FAC_TYPE INNER JOIN ((FAC_REQUEST INNER JOIN STATUS ON FAC_REQUEST.iStatusID = STATUS.iStatusID) ON StateFAC.DVN = FAC_REQUEST.DVN) ON FAC_TYPE.Faciltiy_Type = FAC.FacilityType WHERE iRequestID=" & iRequestID
Thanks

View 6 Replies View Related

Error Incorrect Syntax Near ')'

Mar 7, 2008

Hi,
   When i exceute my report i get the following .. An error occured during local report processing. Query exceuteion failed for dataset 'orders' Incorrect syntax near ')'
If i give NULL i get the above error... But if give one or 2 values it works. but If I run the query in my Sql server mgt studio it works fine too and i run in the BIDS or VS2005 it works fine.. but something happens when i generate the reports... ALTER Procedure [dbo].[usp_GetOrdersByOrderDate]
@ClientId nvarchar(max)= NULL,
@StartDate datetime,
@EndDate datetime
AS
Declare @SQLTEXT nvarchar(max)
If @ClientId IS NULL
Begin
Select
o.OrderId,
o.OrderDate,
o.CreatedByUserId,
c.LoginId,
o.Quantity,
o.RequiredDeliveryDate,
cp.PlanId,
cp.ClientPlanId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId
Inner Join ClientUser c on o.CreatedByUserId = c.UserId
WHERE
--cp.ClientId = @ClientId
--AND
o.OrderDate BETWEEN @StartDate AND @EndDate
ORDER BY
o.OrderId DESC
END
ELSE
BEGIN
SELECT @SQLTEXT = 'Select
o.OrderId,
o.OrderDate,
o.CreatedByUserId,
c.LoginId,
o.Quantity,
o.RequiredDeliveryDate,
cp.PlanId,
cp.ClientPlanId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId
Inner Join ClientUser c on o.CreatedByUserId = c.UserId
WHERE
cp.ClientId in (' + @ClientId + ')
AND
o.OrderDate BETWEEN ' + Convert(varchar,@StartDate) + ' AND ' + convert(varchar, @EndDate) + '
ORDER BY
o.OrderId DESC'
execute (@SQLTEXT)

END
any help will be appreciated.

Regards

Karen
 

View 13 Replies View Related

Incorrect Syntax - Error Help

Jan 14, 2005

Hi! I need some help with this error which I'm unable to understand.

Any help will be highly appreciated.

<Error>
Line 1: Incorrect syntax near 'Number'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'Number'.

Source Error:

Line 69: Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
Line 70: Dim ds As DataSet = New DataSet
Line 71: da.Fill(ds, "Equip")
Line 72:
Line 73: dgdSearch.DataSource = ds.Tables("Equip").DefaultView

Source File: c:inetpubwwwrootEquip logDemoWebForm3.aspx.vb Line: 71

Stack Trace:

[SqlException: Line 1: Incorrect syntax near 'Number'.]
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream)
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
System.Data.SqlClient.SqlCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
System.Data.Common.DbDataAdapter.FillFromCommand(Object data, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable)
Demo.WebForm3.butSearch_Click(Object sender, EventArgs e) in c:inetpubwwwrootEquip logDemoWebForm3.aspx.vb:71
System.Web.UI.WebControls.Button.OnClick(EventArgs e)
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain() +1292

</Error>


Private Sub butSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butSearch.Click
Dim objConnection As SqlConnection
Dim objCommand As SqlCommand
Dim objAdapter As SqlDataAdapter
Dim objDataReader As SqlDataReader
Dim objDataSet As DataSet
Dim strSearch As String
Dim StrSQLQuery As String
'Dim mySQL As String

'Get Search
strSearch = txtSearch.Text

'If there's nothing to search for then don't search
' o/w build our SQL Query execute it.
If Len(Trim(strSearch)) > 0 Then
'Set up our connection.
Dim strConn As String = ("server=(local);Integrated Security=SSPI;database=Equipment Log")

'-- setup the select command
Dim mySQL As String = "Select * From Equip Where " & ddlSearch.SelectedValue.ToString() & " Like '" & txtSearch.Text & " %' Order by DemoNum"

Dim MyConn As New SqlConnection(strConn)
'--create the SqlCommand object (a connection would need to be set up too)
Dim cmd As SqlCommand = New SqlCommand(mySQL, MyConn)
MyConn.Open()
'--execute the query and fill a dataset with the results
Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim ds As DataSet = New DataSet
da.Fill(ds, "Equip")

dgdSearch.DataSource = ds.Tables("Equip").DefaultView

'Create new command object passing it our SQL Query
'and telling it which connection to use.
objCommand = New SqlCommand(strSearch, objConnection)

'DataBind DG to DS
ddlSearch.DataBind()
dgdSearch.DataBind()
MyConn.Close()

Else
txtSearch.Text = "Enter Serach Here"
End If

View 1 Replies View Related

Incorrect Syntax Error?

Jan 2, 2006

I am getting the following error when attempting to call a certain function:
"Incorrect Syntax near spListPrograms, Line 1"
Here is the sproc:
ALTER PROCEDURE spListPrograms
@parentID int = 0
AS
SELECT pwbsID, pwbsTitle FROM ProgramWBS WHERE pwbsParent = @parentID
It is being called from this function:
    Public Shared Function ListProgramChildNodes(Optional ByVal parentID As Integer = 0) As SqlDataReader
        Dim cmd As New SqlCommand("spListPrograms", strConn)
        cmd.Parameters.AddWithValue("@parentID", parentID)
        Try
            strConn.Open()
            Return cmd.ExecuteReader(CommandBehavior.CloseConnection)
 
        Catch e As SqlException
            Dim errorMessages As String = ""
            Dim i As Integer
 
            For i = 0 To e.Errors.Count - 1
                errorMessages += "Index #" & i.ToString() & ControlChars.NewLine _
                               & "Message: " & e.Errors(i).Message & ControlChars.NewLine _
                               & "LineNumber: " & e.Errors(i).LineNumber & ControlChars.NewLine _
                               & "Source: " & e.Errors(i).Source & ControlChars.NewLine _
                               & "Procedure: " & e.Errors(i).Procedure & ControlChars.NewLine
            Next i
 
            MsgBox(errorMessages)
        Finally
            strConn.Close()
        End Try
    End Function
 
The sproc works just fine when I execute it from the database directly in SQl Express. What could cause an incorrect syntax error? There's hardly any syntax there for an error to occur  Thanks for any help you can give me.

View 2 Replies View Related

Incorrect Syntax Error

Mar 8, 2004

hi. i am relatively new to sql. i am wondering how to resolve my "incorrect syntax error" on an IP Address string i am trying to add.
the table has IPAddress as data type "text" and length 16 (which won't let me change the length). It seems that sql is looking for a data type with no more than one decimal (money, float, etc). How do i resolve this? thanks in advance. Peter

View 7 Replies View Related

Syntax Error When Building Up A Where Clause In Stored Procedure

Aug 9, 2006

Can anyone tell me why the line highlighted in blue produces the following error when I try to run this stored proc? I know the parameters are set properly as I can see them when debugging the SP.
I'm using this type of approach as my application is using the objectdatasource with paging. I have a similar SP that doesn't have the CategoryId and PersonTypeId parameters and that works fine so it is the addition of these new params that has messed up the building of the WHERE clause
The Error is: "Syntax error converting the varchar value '  WHERE CategoryId = ' to a column of data type int."
Thanks
Neil
CREATE PROCEDURE dbo.GetPersonsByCategoryAndTypeByName (@CategoryId int, @PersonTypeId int, @FirstName varchar(50)=NULL, @FamilyName varchar(50)=NULL, @StartRow int, @PageSize int)
AS
Declare @WhereClause varchar(2000)Declare @OrderByClause varchar(255)Declare @SelectClause varchar(2000)
CREATE TABLE #tblPersons ( ID int IDENTITY PRIMARY KEY , PersonId int , TitleId int NULL , FirstName varchar (50)  NULL , FamilyName varchar (50)  NOT NULL , FullName varchar (120)  NOT NULL , AltFamilyName varchar (50)  NULL , Sex varchar (6)  NULL , DateOfBirth datetime NULL , Age int NULL , DateOfDeath datetime NULL , CauseOfDeathId int NULL , Height int NULL , Weight int NULL , ABO varchar (3)  NULL , RhD varchar (8)  NULL , Comments varchar (2000)  NULL , LocalIdNo varchar (20)  NULL , NHSNo varchar (10) NULL , CHINo varchar (10)  NULL , HospitalId int NULL , HospitalNo varchar (20)  NULL , AltHospitalId int NULL , AltHospitalNo varchar (20)  NULL , EthnicGroupId int NULL , CitizenshipId int NULL , NHSEntitlement bit NULL , HomePhoneNo varchar (12)  NULL , WorkPhoneNo varchar (12)  NULL , MobilePhoneNo varchar (12)  NULL , CreatedBy varchar(40) NULL , DateCreated smalldatetime NULL , UpdatedBy varchar(40) NULL , DateLastUpdated smalldatetime NULL, UpdateId int )
SELECT @OrderByClause = ' ORDER BY FamilyName, FirstName'
SELECT @WhereClause = '  WHERE CategoryId = ' +  @CategoryId + ' AND PersonTypeId = ' + @PersonTypeIdIf NOT @Firstname IS NULLBEGIN SELECT @WhereClause = @WhereClause + ' AND FirstName LIKE ISNULL(''%'+ @FirstName + '%'','''')'ENDIf NOT @FamilyName IS NULLBEGIN SELECT @WhereClause = @WhereClause + ' AND (FamilyName LIKE ISNULL(''%'+ @FamilyName + '%'','''') OR AltFamilyName LIKE ISNULL(''%'+ @FamilyName + '%'',''''))'END
Select @SelectClause = 'INSERT INTO #tblPersons( PersonId, TitleId, FirstName, FamilyName , FullName, AltFamilyName, Sex, DateOfBirth, Age, DateOfDeath, CauseOfDeathId, Height, Weight, ABO, RhD, Comments, LocalIdNo, NHSNo, CHINo, HospitalId, HospitalNo, AltHospitalId, AltHospitalNo, EthnicGroupId, CitizenshipId, NHSEntitlement, HomePhoneNo, WorkPhoneNo, MobilePhoneNo, CreatedBy, DateCreated, UpdatedBy, DateLastUpdated, UpdateId)
SELECT  PersonId, TitleId, FirstName, FamilyName , FullName, AltFamilyName, Sex, DateOfBirth, Age, DateOfDeath, CauseOfDeathId, Height, Weight, ABO, RhD, Comments, LocalIdNo, NHSNo, CHINo, HospitalId, HospitalNo, AltHospitalId, AltHospitalNo, EthnicGroupId, CitizenshipId, NHSEntitlement, HomePhoneNo, WorkPhoneNo, MobilePhoneNo, CreatedBy, DateCreated, UpdatedBy, DateLastUpdated, UpdateId
 FROM vw_GetPersonsByCategoryAndType '
EXEC (@SelectClause + @WhereClause +@OrderByClause)

View 1 Replies View Related

Error Stored Procedure Parameters

Feb 17, 2004

Hi i'll get the following error

The SqlParameter with ParameterName 'xxxxx' is already contained by another SqlParameterCollection.

I'am trying to create an dataset in which data of the different connectionpoints are separated into different tables. Herefor i'm using an stored procedure.

Below you'll find part of the main function and the full function which will execute the stored procedure.

kind regards


main function

Dim Parameters As SqlParameter() = { _
New SqlParameter("@ConnectionPointID", SqlDbType.NVarChar, 255)}


For x = 0 To myds.Tables("ConnectionPoints").Rows.Count - 1
connectionpointID = myds.Tables("connectionpoints").Rows(x).Item("Eancode")
Parameters(0).Value = connectionpointID
mydb.doStoredProcedure("SP_EDS_Dyomes_XML", Parameters,connectionpointID.ToString, myds)
Next



Public Overloads Function doStoredProcedure( _
ByRef Mycommand As SqlCommand, _
ByRef myds As DataSet, _
ByVal Table As String)


Dim myda As New SqlDataAdapter

Mycommand.CommandTimeout = 180
If Mycommand.Connection Is Nothing Then
Dim mydb As New Database
Mycommand.Connection = mydb.generateconnection
End If
If Mycommand.Connection.State = ConnectionState.Closed Then
Mycommand.Connection.Open()
End If
CheckParameters(Mycommand)
myda.SelectCommand = Mycommand

Try
myda.Fill(myds, Table)
Catch ex As Exception
Debug.Write(ex.Message)
End Try
myda.Dispose()
Mycommand.Dispose()

End Function

View 3 Replies View Related

Incorrect Syntax Near The Keyword 'from'. Line 1: Incorrect Syntax Near ')'.

May 27, 2008

This is the error it gives me for my code and then it calls out line 102.  Line 102 is my  buildDD(sql, ddlPernames)  When I comment out this line the error goes away, but what I don't get is this is the same way I build all of my dropdown boxes and they all work but this one.  Could it not like something in my sql select statement.  thanksPrivate Sub DDLUIC_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DDLUIC.SelectedIndexChanged
Dim taskforceID As Byte = ddlTaskForce.SelectedValueDim uic As String = DDLUIC.SelectedValue
sql = "select sidstrNAME_IND from CMS.dbo.tblSIDPERS where sidstrSSN_SM in (Select Case u.strSSN from tblAssignedPersonnel as u " _
& "where u.bitPresent = 1 and u.intUICID in (select intUICID from tblUIC where intTaskForceID = " & taskforceID & " and strUIC = '" & uic & "'))"ddlPerNames.Items.Add(New ListItem("", "0"))
buildDD(sql, ddlPerNames)
 
End Sub

View 2 Replies View Related

I Am Trying To Use A Stored Proc To Page Thru Table But It Is Saying Incorrect Syntax Near GO

Aug 24, 2007

Can anyone helpCREATE PROCEDURE PagedResults_New
(@startRowIndex int,
@maximumRows int
)
AS
 
--Create a table variable
DECLARE @TempItems TABLE
(ID int IDENTITY,
ShortListId int
)
-- Insert the rows from tblItems into the temp. table
INSERT INTO @TempItems (ShortListId)
SELECT Id
FROM shortlist SWHERE Publish = 'True' order by date DESC
 
-- Now, return the set of paged records
SELECT S.*, C.CategoryTitleFROM @TempItems t
INNER JOIN shortList S ON
t.ShortListId = S.Id
 WHERE ID BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1
GO

View 1 Replies View Related

Error While Creating A Stored Procedure

Aug 30, 2012

I am working with SQL Server 2005 Express and have written a query which works well in when run it in the managment console as a select query.

When I try to create a stored procedure out of it, I get the following error:

Code:
Msg 102, Level 15, State 1, Procedure sp_SegmentationList_ByorderID, Line 20 Incorrect syntax near ';'.

Procedure is below:

Code:
USE [ARC_Test]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_SegmentationList_ByorderID]
@OrderID int

[code].....

View 3 Replies View Related

Error 156: Incorrect Syntax Near The Keyword WHEN.

Jan 16, 2008

Hi i have the following code in my sql database;CASE dbo.tblWorkSchedule.WorkScheduleType_ID WHEN 1 THENCASE IsNull(dbo.tblSurvey.WorkScheduleOverallStatus_ID,0) WHEN 4 THENdbo.tblWorkSchedule.UpliftedRate ELSE dbo.GetSWT_PropertyYearPeriodRate (IsNull(tblRateSchedule.WorkType_ID,0)  ,tblWorkSchedule.WorkSchedule_ID  , tblSurvey.PropertyYear_ID , tblSurvey.PropertyPeriod_ID )  END   I want to add the following lines to it, however it gives me an error "Error 156: Incorrect syntax near the keyword "WHEN". What do i need to do, thank you.  WHEN 3 THEN dbo.tblWorkSchedule.UpliftedRate ELSE dbo.GetSWT_PropertyYearPeriodRate (IsNull(tblRateSchedule.WorkType_ID,0)  ,tblWorkSchedule.WorkSchedule_ID  , tblSurvey.PropertyYear_ID , tblSurvey.PropertyPeriod_ID )  END
 
 

View 7 Replies View Related

Error: Incorrect Syntax Near The Keyword 'WHERE'

Feb 28, 2008

Hi,
I am building a website and database system for a university project, and am getting an error message when inserting data to a table (error message = "System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'WHERE'.").  I would be most grateful if anybody could point out where I am going wrong!  My code is;
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{protected void Page_Load(object sender, EventArgs e)
{if ((Session["sUserName"]) == null)
{Response.Redirect("Default.aspx");
}
else
{Convert.ToString(Session["sUserName"]);
}
}protected void Register(object sender, EventArgs e)
{
//Create the ConnectionSqlConnection sqlConn =
new SqlConnection("server=Acer-Laptop\SQLEXPRESS; database=NeuCar; Trusted_Connection=true");
//Open the connection
sqlConn.Open();
//Create the Command, passing in the SQL statement and the ConnectionString queryString = "INSERT INTO Member (FirstName, LastName, Title, Email, AddressLine1, AddressLine2, TownOrCity, County, Postcode) VALUES(@myFirstName, @myLastName, @myTitle, @myEmail, @myAddressLine1, @myAddressLine2, @myTownOrCity, @myCounty, @myPostcode) WHERE Member (UserName = @myUserName); ";
SqlCommand cmd = new SqlCommand(queryString, sqlConn);cmd.Parameters.Add(new SqlParameter("@myUserName", Session["sUserName"]));
cmd.Parameters.Add(new SqlParameter("@myFirstName", FirstNameTextBox.Text));cmd.Parameters.Add(new SqlParameter("@myLastName", LastNameTextBox.Text));
cmd.Parameters.Add(new SqlParameter("@myTitle", TitleTextBox.Text));cmd.Parameters.Add(new SqlParameter("@myEmail", ConfirmEmailTextBox.Text));
cmd.Parameters.Add(new SqlParameter("@myAddressLine1", AddressLine1TextBox.Text));cmd.Parameters.Add(new SqlParameter("@myAddressLine2", AddressLine2TextBox.Text));
cmd.Parameters.Add(new SqlParameter("@myTownOrCity", TownOrCityTextBox.Text));cmd.Parameters.Add(new SqlParameter("@myCounty", CountyTextBox.Text));cmd.Parameters.Add(new SqlParameter("@myPostcode", PostcodeTextBox.Text));
cmd.ExecuteNonQuery();
Response.Redirect("Register.aspx");
//Close the connection
sqlConn.Close();
}
}
Also, is this line of code correct for passing a session variable into a parameter?;
cmd.Parameters.Add(new SqlParameter("@myUserName", Session["sUserName"]));
Many thanks for your time and help!
Chima

View 5 Replies View Related

Error-Line 1: Incorrect Syntax Near '='

Aug 21, 2004

hi,

i got this error when i run app.

---------------
Line 1: Incorrect syntax near '='.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near '='.

Source Error:


Line 40: Dim adpt As New SqlDataAdapter("SELECT * FROM SMS_student_class_master WHERE" & _
Line 41: "stud_id=" & sid, con)
Line 42: adpt.Fill(ds, "SMS_student_class_master")
Line 43: txt.Text = ds.Tables.Item("roll_no").ToString
Line 44: con.Close()


Source File: c:inetpubwwwrootaspnetsmsassignment_d.aspx.vb Line: 42
--------

what should i do?
anyone have any idea?
plz give solution.
it's urgent.

thanks in advance

View 2 Replies View Related

Incorrect Syntax Near &#39;s&#39; Error Message

May 10, 2000

I am moving along but I still get this pesky error. In a field on the user form for comments - when there is a ' character - I get this syntax error. But, I have removed the ' character with this code:
fieldname= Replace(Request.Form("fieldname"), "'", " ")

So how do I get rid of this error? Beats me.
Anyone know of resources I can read about this?

Thanks in advance...................


Set objConn = Server.CreateObject("ADODB.Connection")
Set rs = server.createobject("ADODB.Recordset")

objConn.open "Driver={SQL Server};Server=server;DSN=SQL3;Database=requests;U ID=probe;PWD=;"

strDocument= request.form("qryName")
strName= request.form("name")
strDescription= request.form("description")
strEmail= request.form("email")
StrTeam= request.form("shift")
StrSection= request.form("pickone")
StrComments= request.form("comments")
StrDatein= request.form("datein")
StrType= request.form("type")
StrDcfnumber=CounterHits



sql = "Insert into dcf_submit (qryName,name,description,email_requestor,shift,se ction_pickone,change_type,comments,date_submit,dcf _number) values('" & _
strDocument & "','" & _
strName & "','" & _
strDescription & "','" & _
strEmail & "','" & _
StrTeam & "','" & _
StrSection & "','" & _
StrType & "','" & _
StrComments & "','" & _
StrDatein & "','" & _
StrDcfnumber & "')"

objConn.execute sql

rs.Close
Set rs = Nothing

View 1 Replies View Related

Error - Incorrect Syntax Near Rename

Mar 14, 2012

----change In the name of Table 5 Table 6

Use test
GO
ALTER TABLE NAME tablo5 RENAME TO tablo6;
GO

but error messages::

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'tablo5'.
------------------
------------------
----tablo4 d1 ==> d11 change.
Use test
GO
ALTER TABLE tablo4 RENAME COLUMN d1 TO d11;
GO

error messages::

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'RENAME'

View 1 Replies View Related

Error - Incorrect Syntax Near The Keyword (else)

Nov 12, 2014

I am getting error "Incorrect syntax near the keyword 'else'"

below is my code

declare @a varchar(15), @b Float(12) ,@c Float(12),@m varchar(15),@n Float(15),@av Float(15),@xav float(15)
SELECT @a=reverse(Substring(reverse(remarks),Charindex('tS',REVERSE(remarks))+2,4))
FROM [IVRS_MIS].[dbo].[logs] where app_name='IVFRT_POC' and remarks like '%answered%'
if @a = 1020
SELECT @m = '1022', @n = Count(@a), @av = Count(@a)/4.0 ,@b = substring(MAX(right(node_info, charindex('X',reverse(node_info))-8)),1,5) ,@c=substring(MIN(right(node_info, charindex('X',reverse(node_info))-8)),1,5),@xav=(@b+@c)/2.0
FROM [IVRS_MIS].[dbo].[logs]

[code].....

View 2 Replies View Related

Strange Incorrect Syntax Error

Jul 12, 2007

Hey guys, I'm getting this really strange incorrect sytax error with a program I'm writing in VB.NET for an ASP.NET website.



Here is my code:



Dim mySelectQuery2 As String = "SELECT MAX(TicketID) FROM tblTicket"

Dim myInsertQuery As String = "INSERT INTO tblCaller (TicketID)"

Dim myConnection As New Data.SqlClient.SqlConnection(myConnString)

Dim myCommand As New Data.SqlClient.SqlCommand(mySelectQuery2, myConnection)

Dim myCommand2 As New Data.SqlClient.SqlCommand(myInsertQuery, myConnection)

Dim retvalue As Integer

myConnection.Open()

retvalue = myCommand2.ExecuteNonQuery()

Console.WriteLine(retvalue)

Dim myReader2 As Data.SqlClient.SqlDataReader

myReader2 = myCommand.ExecuteReader()

myReader2.Close()

myConnection.Close()



Now, the actual error I'm getting is "Incorrect syntax near ')'." that is refering to the link of code "retvalue = myCommand2.ExecuteNonQuery()". I've played around with the code a little bit but I just can't seem to make that error go away.



My only guess is that in the "myInsertQuery" I should have "VALUE (...", but I'm not sure what to put there.



If anyone could make any suggestions on what I might want to try, or if you think that you need more information please let me know.



Thanks,

aqzman

View 5 Replies View Related

XML Query Error Incorrect Syntax Near '&&<'

Feb 6, 2007

Hi all,

I use

="<Query><XmlData>" & Parameters!XMLData.Value & "</XmlData><ElementPath>Product {@}</ElementPath></Query>"



and I enter XMLData with value "<Products><Product>Chair</Product><Product>Table</Product></Products>"

for the query expression of the dataset, and I always got error:

Query failed for dataset "Dataset1"

Incorrect syntax near '<'



What's wrong with it?



Thanks,

Jone

View 1 Replies View Related

Error Message Incorrect Syntax Near ')'

Mar 10, 2008



Hi,

When i exceute my report i get the following .. An error occured during local report processing. Query exceuteion failed for dataset 'orders' Incorrect syntax near ')'

If i give NULL i get the above error... But if give one or 2 values it works. but If I run the query in my Sql server mgt studio it works fine too and i run in the BIDS or VS2005 it works fine.. but something happens when i generate the report in preview mode. I am using multivalue parameter
This is my sproc



Code Snippet
ALTER Procedure [dbo].[usp_GetOrdersByOrderDate]

@StartDate datetime,
@EndDate datetime,
@ClientId nvarchar(max)= NULL
AS
Declare @SQLTEXT nvarchar(max)
if @ClientId is NULL
BEGIN
SELECT
o.OrderId,
o.OrderDate,
o.CreatedByUserId,
c.LoginId,
o.Quantity,
o.RequiredDeliveryDate,
cp.PlanId,
cp.ClientPlanId
--c.ClientId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId and o.CreatedByUserId = cp.UserId
Inner Join ClientUser c on o.CreatedByUserId = c.UserId
WHERE
--cp.ClientId = @ClientId
--AND
o.OrderDate BETWEEN @StartDate AND @EndDate
ORDER BY
o.OrderId DESC
END
ELSE
BEGIN
SELECT @SQLTEXT = 'Select
o.OrderId,
o.OrderDate,
o.CreatedByUserId,
c.LoginId,
o.Quantity,
o.RequiredDeliveryDate,
cp.PlanId,
cp.ClientPlanId
--cp.ClientId
FROM
[Order] o
Inner Join ClientPlan cp on o.PlanId = cp.PlanId --AND cp.ClientId in ('+ convert(Varchar, @ClientId) + ' )
Inner Join ClientUser c on o.CreatedByUserId = c.UserId
WHERE
cp.ClientId in (' + convert(Varchar,@ClientId) + ')
AND
o.OrderDate BETWEEN ''' + Convert(varchar, @StartDate) + ''' AND ''' + convert(varchar, @EndDate) + '''
ORDER BY
o.OrderId DESC'
exec(@SQLTEXT)
END





any help will be appreciated..

Thanks
Karen

View 14 Replies View Related

JDBC Error Incorrect Syntax Near '-'.

Sep 18, 2007

Hi I am using JDBC driver version "1.0.809.102". In the ms sqlserver 2000 database I am acessing there is a table named as "CDR_DATA_2007-09-12". When I run the following query "select * from CDR_DATA_2007-09-12" i get the following exception. Please help me out to solve this problem.

com.microsoft.sqlserver.jdbc.SQLServerException: Line 1: Incorrect syntax near '-'. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(Unknown Source) at com.microsoft.sqlserver.jdbc.TDSCommand.execute(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(Unknown Source) at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(Unknown Source) at Test.mssqldb(Test.java:80) at Test.main(Test.java:26) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:86)

Thanks,Gavin

View 3 Replies View Related

Application Given En Error When Parameters In Stored Procedure Is Changes

Apr 26, 2008

Hi,I am developing application in asp.net 2.0 using C#. My back end is sql server 2005. I also use microsoft enterprise library 2006.My problem is:First i pass three parameters to stored procedure from the application. After i increase one more parameter in both application as well as stored procedure, the application gives an error that parameter does not match with the stored procedures parameters.after couple of hours when i restart the machine and again run the application it works fine with four parameters.does sql server 2005 stores the parameters in cache??

View 3 Replies View Related

Stored Procudure With Multiple Select... Incorrect Syntax Near 'storedProcedure'

Mar 8, 2004

Hi,

Im fairly new to writing stored procudures so I thought you lot might be able to help with this problem.

I have a stored procudure which looks like this:

CREATE PROCEDURE usrCienet.spAdminAgencyActivate_Select
(
@strAgencyId CHAR(6)
)

AS

DECLARE @idAgency INT

SELECT @idAgency = idAgency FROM tblAgencies WHERE strAgencyId = @strAgencyId;

SELECT strName, strAddress1, strAddress2, strCounty, strCountry, strPostcode, strTelephone, strFax, bitActive, bitHeadOffice, bitFinanceBranch
FROM tblBranches
WHERE fk_idAgency = @idAgency

SELECT strFirstName, strSurname, strUsername, bitActive
FROM tblUsers
WHERE fk_idAgency = @idAgency

GO

It basically first declare's and sets @idAgency using the first small select statment, then uses that parameter to run two more selects queries which I want sending to a dataset. Now within the Query Analyzer this works fine. But in my asp.net page it trows up this error:

Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'spAdminAgencyActivate_Select'

Now the code im using in the asp.net page is as follows:


Dim objSqlConnection as New SqlConnection(ConfigurationSettings.AppSettings("strCon"))
Dim objSqlCommand_Select as New SqlCommand("spAdminAgencyActivate_Select", objSqlConnection)

objSqlCommand_Select.Parameters.Add(New SqlParameter("@strAgencyId", SqlDbType.Char, 6))
objSqlCommand_Select.Parameters("@strAgencyId").Value = "tes001"

Dim objSqlDataAdapter as New SqlDataAdapter(objSqlCommand_Select)

Dim dsActivateAgency as New DataSet()

objSqlConnection.Open()
objSqlDataAdapter.TableMappings.Add("Table", "tblBranches")
objSqlDataAdapter.TableMappings.Add("Table1", "tblUsers")
objSqlDataAdapter.Fill(dsActivateAgency)
objSqlConnection.Close()


Can anyone help? I believe the error is in the stored procedure somewhere, because if I change the stored procedure so no parameters are being passed to it then it starts working. This is what I comment out and change for it to to get it working, but obviously this is not satisfactory as a final result because the parameter is hard coded in the stored procedure. Im just showing this to see if it gives anyone a clue!!

CREATE PROCEDURE usrCienet.spAdminAgencyActivate_Select
--(
--@strAgencyId CHAR(6)
--)

AS

--DECLARE @idAgency INT

--SELECT @idAgency = idAgency FROM tblAgencies WHERE strAgencyId = @strAgencyId;

SELECT strName, strAddress1, strAddress2, strCounty, strCountry, strPostcode, strTelephone, strFax, bitActive, bitHeadOffice, bitFinanceBranch
FROM tblBranches
WHERE fk_idAgency = 1

SELECT strFirstName, strSurname, strUsername, bitActive
FROM tblUsers
WHERE fk_idAgency = 1

GO

Thanks in advance for any help!!

- Carl S

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved