問題描述
我正在嘗試從同一個(gè) .sql 文件中創(chuàng)建多個(gè)用戶定義的函數(shù).我正在使用 SQL Server 并使用 C# 的 System.Data
中的 SqlClient
執(zhí)行我的查詢.
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
.
.sql 文件的內(nèi)容:
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
這是我執(zhí)行語句時(shí)拋出的錯(cuò)誤:
Here's the error that is thrown when I execute the statement:
System.Data.SqlClient.SqlException: 'GO' 附近的語法不正確.
必須聲明標(biāo)量變量@username2".
'END' 附近的語法不正確.
System.Data.SqlClient.SqlException: 'Incorrect syntax near 'GO'.
Must declare the scalar variable "@username2".
Incorrect syntax near 'END'.'
有什么想法嗎?總的來說,我是 SQL 的新手,但這對我來說似乎是缺乏對語法/批處理的理解.
Any ideas? I'm new to SQL in general but this seems to be a lack of understanding syntax/batching to me.
我注意到GO"是 SQL Server Management Studio 的一部分,而不是 SqlClient
.如果我從 .sql 文件中刪除GO",則會(huì)收到此錯(cuò)誤:
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' 必須是查詢批處理中的第一條語句.
'CREATE FUNCTION' must be the first statement in a query batch.
如何在不使用GO"的情況下分隔 CREATE FUNCTION
語句?
How do I separate CREATE FUNCTION
statements without using 'GO'?
推薦答案
您不能在單個(gè)語句中運(yùn)行多個(gè)批處理.
You cannot run multiple batches in a single statement.
我建議您使用 GO 拆分 TSQL 語句,然后逐個(gè)執(zhí)行批處理.
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();
}
這篇關(guān)于無法使用 System.Data.SqlClient 在 SQL Server 中創(chuàng)建多個(gè)用戶定義的函數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!