Run a .sql statement with keyword GO using C#?

Viewed 116

I have the following

USE [TESTDB]
CREATE FUNCTION dbo.Function1 (@input VARCHAR(250)) 
RETURNS VARCHAR(250) 
AS 
BEGIN   
 --do work here
END

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON

CREATE FUNCTION dbo.Function2 (@input VARCHAR(250)) 
RETURNS VARCHAR(250) 
AS BEGIN   
 --do work here
END

I tried to run this with my SQL connection in C#, but get the error:

CREATE FUNCTION' must be the first statement in a query batch. Must declare the scalar variable "@input ".

How can I run this in C#?

1 Answers

GO is not a SQL concept; it literally doesn't exist in the syntax.

SSMS allows it by parsing the SQL, and recognizing GO (and GO {integer}) usage, and splits your command into pieces; it then issues those pieces separately one after the other as independent commands. It is entirely SSMS, not the SQL Server driver or the SQL Server database/server, that does this. SqlClient (the ADO.NET provider) does not have this functionality built in to mimic SSMS, so: you'd need to implement it in your own code. Or perhaps easier: just write your code as separate commands in the first place.

Related