Solved

Trying to execute multiple t-sql statements in single t-sql call in vb.net

Posted on 2013-01-25
7
211 Views
Last Modified: 2013-01-30
The below code is failing with the following error

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near the keyword 'CREATE'.
Must declare the scalar variable "@CogsdaleId".
Incorrect syntax near 'GO'.

The t-sql code works in mssql server, but not when executed in vb using the following code

   Dim results As System.Data.SqlClient.SqlDataReader
            Dim connect As System.Data.SqlClient.SqlConnection = New System.Data.SqlClient.SqlConnection()
            Dim callFunctionStr As New System.Data.SqlClient.SqlCommand()


            connect.ConnectionString = Application("DefaultConnectionString")
            callFunctionStr.Connection = Session("conn")

            callFunctionStr.CommandText = My.Resources.getcurbalance
            callFunctionStr.Connection.Open()

            results = callFunctionStr.ExecuteReader

Open in new window


This is the contents of the resource file (which is a .sql file)

IF EXISTS (select * from dbo.sysobjects where id = object_id(N'Cogsdale_getMostRecentBill') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
	DROP PROCEDURE Cogsdale_getMostRecentBill
END
GO

CREATE PROCEDURE [dbo].[Cogsdale_getMostRecentBill]
	@CogsdaleId		varchar(13)
AS
DECLARE @FID	INT
DECLARE @SID	INT
DECLARE	@SDATE	DATETIME

DECLARE @tmpStatements TABLE
(
	fld_ID	INT	IDENTITY,
	CogsdaleId	char(13),
	StatementNumber	int,
	StatementDate	datetime,
	BilledAMT	float,
	OutstandingAMT	float,
	DueDate	datetime,
	Status	char(8)
)

INSERT INTO @tmpStatements(CogsdaleID,StatementNumber,StatementDate,BilledAMT)
SELECT TOP 1
	RTRIM(B.umLocationID) + '-' + RTRIM(A.CUSTNMBR) AS CogsdaleId,
	A.umStatementDocNo AS StatementNumber,
	C.umDocDate AS StatementDate,
	A.umStatementAmount AS BilledAMT
FROM UM00701 AS A
	inner join UM00600 AS B ON A.umLocationID = B.umLocationID
	inner join um00702 AS D ON A.umStatementDocNo = D.umStatementDocNo
	inner join UM42300 AS C ON D.umDocumentNumber = C.umDocumentNumber
WHERE A.CUSTNMBR = RIGHT(@CogsdaleId,6)	AND C.umDocType IN (5,15,14) AND NOT C.umDocLoc = 1 AND B.umLocationID = LEFT(@CogsdaleId,6)
ORDER BY A.umLocationID, A.umStatementDate DESC

DECLARE curBill CURSOR FOR
	SELECT fld_ID,StatementNumber,StatementDate FROM @tmpStatements

OPEN curBill
FETCH NEXT FROM curBill
INTO @FID,@SID,@SDATE

	WHILE @@FETCH_STATUS = 0
		BEGIN
			DECLARE @outstandingAMT	float
			SELECT @outstandingAMT = ISNULL(SUM(umOutstandingAmt), 0.00)
			FROM
						(SELECT umOutstandingAmt
						FROM UM20400
						WHERE umDocumentNumber IN (SELECT umDocumentNumber FROM UM00702 WHERE umStatementDocNo = @SID)
						union 
						(select BilledAMT from @tmpStatements)) Docs
			
			IF @outstandingAMT = 0
				BEGIN
					UPDATE @tmpStatements SET OutstandingAMT = @outstandingAMT, Status='PAID' WHERE StatementNumber = @SID
				END
			ELSE IF @outstandingAMT > 0
				BEGIN
					IF GETDATE() > DATEADD(dd,30,@SDATE) AND @FID <> 1
						BEGIN
							UPDATE @tmpStatements SET OutstandingAMT = @outstandingAMT, Status='PAST DUE' WHERE StatementNumber = @SID
						END
					ELSE
						BEGIN
							UPDATE @tmpStatements SET OutstandingAMT = @outstandingAMT, Status='PAY' WHERE StatementNumber = @SID
						END
				END

			UPDATE @tmpStatements SET DueDate = DATEADD(dd,30,@SDATE) WHERE StatementNumber = @SID

			FETCH NEXT FROM curBill
			INTO @FID,@SID,@SDATE
		END
CLOSE curBill
DEALLOCATE curBill
SELECT CogsdaleId,StatementNumber,StatementDate,BilledAMT,OutstandingAMT,DueDate,Status FROM @tmpStatements
GO

Open in new window

0
Comment
Question by:UnderSeven
  • 4
  • 2
7 Comments
 
LVL 28

Expert Comment

by:Ryan McCauley
ID: 38819649
The CREATE PROCEDURE statement isn't formatted correctly - it's missing some perentheses. Lines 7-9 should be:

CREATE PROCEDURE [dbo].[Cogsdale_getMostRecentBill] (
	@CogsdaleId		varchar(13)
) AS

Open in new window

0
 

Author Comment

by:UnderSeven
ID: 38819716
added suggested paranths, no change in error, made sure changes were being accounted for in execution.
0
 

Author Comment

by:UnderSeven
ID: 38819796
Ah got it.  The problem seems to be I can't create procs in statement files that include preceeding statements.

If anyone know of a way I could do that then I'd love to hear.
0
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 

Accepted Solution

by:
UnderSeven earned 0 total points
ID: 38820164
Turns it out was the use of Go without the use of semi colins.  This works:

IF EXISTS (select * from dbo.sysobjects where id = object_id(N'Cogsdale_getActiveConnections') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
BEGIN
	DROP PROCEDURE Cogsdale_getActiveConnections
END;

CREATE PROCEDURE [dbo].[Cogsdale_getActiveConnections]
	@CogsdaleID	char(13)
AS . . . ect

Open in new window

0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 38823066
Ryan,

The CREATE PROCEDURE statement isn't formatted correctly - it's missing some perentheses. Lines 7-9 should be:

If you are referring to the parenthesis around the parameters they are optional.  See here from SQL Server BOL:
Syntax
 
CREATE { PROC | PROCEDURE } [schema_name.] procedure_name [ ; number ]
    [ { @parameter [ type_schema_name. ] data_type }
        [ VARYING ] [ = default ] [ OUT | OUTPUT ] [READONLY]
    ] [ ,...n ]
[ WITH <procedure_option> [ ,...n ] ]
[ FOR REPLICATION ]
AS { <sql_statement> [;][ ...n ] | <method_specifier> }
[;]
<procedure_option> ::=
    [ ENCRYPTION ]
    [ RECOMPILE ]
    [ EXECUTE AS Clause ]

<sql_statement> ::=
{ [ BEGIN ] statements [ END ] }

<method_specifier> ::=
EXTERNAL NAME assembly_name.class_name.method_name
 
0
 
LVL 28

Expert Comment

by:Ryan McCauley
ID: 38824964
acperkins: You're right - I've always used the perentheses and didn't realize they were optional. That's what I get for rushing through :(
0
 

Author Closing Comment

by:UnderSeven
ID: 38834555
This was the only solution that solved the problem.
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question