Search code examples
sqlsql-servert-sql

Unable to Create Multiple User Defined Functions in SQL Server Using System.Data.SqlClient


I am trying to create multiple user defined functions from within the same .sql file. I am using SQL Server and am executing my queries using the SqlClient from C#'s System.Data.

Contents of the .sql file:

CREATE FUNCTION [dbo].[GetUserId] (@username VARCHAR(32))
RETURNS INT
AS
BEGIN
    DECLARE @userId INT = -1

    SET @userId = (SELECT DISTINCT UserId FROM Users WHERE UserName = @username)

    RETURN @userId
END
GO

CREATE FUNCTION [dbo].[GetUserId2] (@username2 VARCHAR(32))
RETURNS INT
AS
BEGIN
    DECLARE @userId2 INT = -1

    SET @userId2 = (SELECT DISTINCT UserId FROM Users WHERE UserName = @username2)

    RETURN @userId2
END

Here's the error that is thrown when I execute the statement:

System.Data.SqlClient.SqlException: 'Incorrect syntax near 'GO'.
Must declare the scalar variable "@username2".
Incorrect syntax near 'END'.'

Any ideas? I'm new to SQL in general but this seems to be a lack of understanding syntax/batching to me.

EDIT: It has come to my attention that 'GO' is part of SQL Server Management Studio, and not the SqlClient. If I remove the 'GO' from my .sql file, then I get this error:

'CREATE FUNCTION' must be the first statement in a query batch.

How do I separate CREATE FUNCTION statements without using 'GO'?


Solution

  • You cannot run multiple batches in a single statement.

    I would suggest you to split your TSQL statement using GO and then execute the batches one by one.

    string multipleUDFs = "CREATE FUNCTION... " +
    "GO" + 
    "CREATE FUNCTION ";
    List<string> statementsToExecute = multileUDFs.Split("GO").ToList();
    
    // Create the command 
    var command = new SqlCommand(myConnection);
    
    foreach(string sqlcommand in statementsToExecute)
    {
    
    // Change the SQL Command and execute
    command.CommandText = sqlcommand;
    command.ExecuteNonQuery();
    }