我有一个带有GO
批处理分隔符的SQL脚本,我试图从C#代码执行。当我使用Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery
时,效果很好。不过,它会在Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteReader
或Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteWithResults
上爆炸。
System.AggregateException: One or more errors occurred. --->
Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. --->
System.Data.SqlClient.SqlException: Incorrect syntax near 'GO'.
这是一个非常简单的脚本,如下所示:
SELECT
DB_NAME()
AS
'Database Name';
GO
EXEC [schema].[MyStoredProcedure];
GO
SELECT
[Column]
AS
'Friendly Column Name'
FROM
[schema].[Table];
GO
我尝试了script.Replace("\n", "\r\n")
,得到的结果相同。有谁知道如何执行这样的脚本和得到结果?
答案 0 :(得分:-1)
ExecuteReader和ExecuteWithResults不识别批处理分隔符GO。最简单的方法是删除脚本中的GO并调用ExecuteWithResults
脚本
SELECT
DB_NAME()
AS
'Database Name';
EXEC [schema].[MyStoredProcedure];
SELECT
[Column]
AS
'Friendly Column Name'
FROM
[schema].[Table];
代码
DataSet ds = Database.ExecuteWithResults(script);
DataTable dbNameTable = ds.Tables[0]; //Select DB_NAME()
DataTable storedProcedureResults = ds.Tables[1]; //Exec [schema].[MyStoredProcedure]
DataTable queryResults = ds.Tables[2]; //Select [Column] From [Schema].[Table]