我有一个带有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", "rn")
,得到了同样的结果。有人知道我如何执行这样的脚本并返回结果吗?
ExecuteReader和ExecuteWithResults无法识别批处理分隔符GO。最简单的方法就是删除脚本中的GOs并调用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]