2

我有一个带有GO批处理分隔符的 SQL 脚本,我试图从 C# 代码执行。当我使用Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteNonQuery时,效果很好。但是,它在Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteReaderor上爆炸了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"),我得到了相同的结果。有谁知道我如何执行这样的脚本取回结果?

4

1 回答 1

-2

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]
于 2015-11-03T16:47:04.287 回答