Solved

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

Posted on 2013-01-25
7
202 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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Nowadays, some of developer are too much worried about data. Who is using data, who is updating it etc. etc. Because, data is more costlier in term of money and information. So security of data is focusing concern in days. Lets' understand the Au…
Let's review the features of new SQL Server 2012 (Denali CTP3). It listed as below: PERCENT_RANK(): PERCENT_RANK() function will returns the percentage value of rank of the values among its group. PERCENT_RANK() function value always in be…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to shrink a transaction log file down to a reasonable size.

760 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now