GO语句在.NET中炸毁sql执行

时间:2013-09-03 16:10:29

标签: c# .net sql-server

我有一个非常简单的C#命令shell应用程序,它执行SQL Server生成的sql脚本,用于脚本架构和数据。它正在吹嘘“GO”声明。错误讯息:

  

'GO'附近的语法不正确。

这是完整的sql脚本:

/****** Object:  Table [gym].[MembershipStatus]    Script Date: 9/3/2013 9:24:01 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [gym].[MembershipStatus](
    [MembershipStatusID] [tinyint] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](75) NOT NULL,
    [Description] [varchar](400) NOT NULL,
    [AllowCheckin] [bit] NOT NULL,
    [IncludeInCollections] [bit] NOT NULL,
    [ScheduleFutureInvoices] [bit] NOT NULL,
 CONSTRAINT [MembershipStatus_PK] PRIMARY KEY CLUSTERED 
(
    [MembershipStatusID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [gym].[MembershipStatus] ON 

INSERT [gym].[MembershipStatus] ([MembershipStatusID], [Name], [Description], [AllowCheckin], [IncludeInCollections], [ScheduleFutureInvoices]) VALUES (1, N'Active', N'Active', 1, 1, 1)
INSERT [gym].[MembershipStatus] ([MembershipStatusID], [Name], [Description], [AllowCheckin], [IncludeInCollections], [ScheduleFutureInvoices]) VALUES (2, N'Cancelled', N'Cancelled', 0, 1, 0)
INSERT [gym].[MembershipStatus] ([MembershipStatusID], [Name], [Description], [AllowCheckin], [IncludeInCollections], [ScheduleFutureInvoices]) VALUES (3, N'Collection', N'Collection', 0, 0, 0)
INSERT [gym].[MembershipStatus] ([MembershipStatusID], [Name], [Description], [AllowCheckin], [IncludeInCollections], [ScheduleFutureInvoices]) VALUES (4, N'Deleted', N'Deleted', 0, 0, 0)
INSERT [gym].[MembershipStatus] ([MembershipStatusID], [Name], [Description], [AllowCheckin], [IncludeInCollections], [ScheduleFutureInvoices]) VALUES (5, N'Expired', N'Expired', 1, 1, 1)
INSERT [gym].[MembershipStatus] ([MembershipStatusID], [Name], [Description], [AllowCheckin], [IncludeInCollections], [ScheduleFutureInvoices]) VALUES (6, N'Freeze', N'Freeze', 0, 1, 0)
INSERT [gym].[MembershipStatus] ([MembershipStatusID], [Name], [Description], [AllowCheckin], [IncludeInCollections], [ScheduleFutureInvoices]) VALUES (7, N'Inactive', N'Inactive', 0, 1, 1)
SET IDENTITY_INSERT [gym].[MembershipStatus] OFF
ALTER TABLE [gym].[MembershipStatus] ADD  DEFAULT ('') FOR [Name]
GO
ALTER TABLE [gym].[MembershipStatus] ADD  DEFAULT ('') FOR [Description]
GO
ALTER TABLE [gym].[MembershipStatus] ADD  DEFAULT ((0)) FOR [AllowCheckin]
GO
ALTER TABLE [gym].[MembershipStatus] ADD  DEFAULT ((0)) FOR [IncludeInCollections]
GO
ALTER TABLE [gym].[MembershipStatus] ADD  DEFAULT ((0)) FOR [ScheduleFutureInvoices]
GO

我的代码的相关部分如下所示:

SqlCommand command = new SqlCommand(script, connection);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();

有什么想法吗?

11 个答案:

答案 0 :(得分:31)

正如其他人所提到的,用GO语句拆分字符串。但要小心,您可能在脚本的其他部分中包含文本"GO"。在GO语句之前或之后,您可能还有空格,并且您可能也会在GO语句之后对该行进行注释。任何这些都在SSMS中有效,所以你可能想要测试它。

以下是我使用的方法:

private static IEnumerable<string> SplitSqlStatements(string sqlScript)
{
    // Split by "GO" statements
    var statements = Regex.Split(
            sqlScript,
            @"^[\t ]*GO[\t ]*\d*[\t ]*(?:--.*)?$",
            RegexOptions.Multiline |
            RegexOptions.IgnorePatternWhitespace |
            RegexOptions.IgnoreCase);

    // Remove empties, trim, and return
    return statements
        .Where(x => !string.IsNullOrWhiteSpace(x))
        .Select(x => x.Trim(' ', '\r', '\n'));
}

答案 1 :(得分:26)

如果您希望能够使用GO,则需要参考以下dll

  

Microsoft.SqlServer.ConnectionInfo.dll
  Microsoft.SqlServer.Management.Sdk.Sfc.dll
  Microsoft.SqlServer.Smo.dll Microsoft.SqlServer.SqlEnum.dll

然后像这样执行

 using (SqlConnection conn = new SqlConnection(connection))
 {
     Server db = new Server(new ServerConnection(conn));
     string script = File.ReadAllText(scriptPath);
     db.ConnectionContext.ExecuteNonQuery(script);      
 }

答案 2 :(得分:11)

GO不是SQL的一部分,它是SQL Server Management Studio为您分割脚本所做的事情。

您需要做的是将查询读入字符串然后在GO上单独拆分(您可能需要使用正则表达式)

//Its better to dispose the SqlCommand, I also switched constructors so I could re-use the SqlCommand.
using(SqlCommand command = new SqlCommand())
{
    command.Connection = connection;

    var scripts = Regex.Split(script, @"^\w+GO$", RegexOptions.Multiline);
    foreach(var splitScript in scripts)
    {
        command.CommandText = splitScript;
        command.ExecuteNonQuery();
    }
}

Matt Johnson's answer查看GO分裂的不太天真的实现。

答案 3 :(得分:7)

GO不是有效的QA命令,它是批处理分隔符......企业管理器将其处理以分离SQL脚本。因此,它可以在企业管理器中工作,但不能在C#或其他外部程序的数据库调用中工作....

答案 4 :(得分:2)

作为按摩脚本以使其可通过C#运行的替代方法,您可以使用sqlcmd实用程序按原样运行它们。很多细节在:

http://technet.microsoft.com/en-us/library/ms180944.aspx

通过使用sqlcmd,您可以编写执行任意数量的SQL Server生成的脚本的脚本,而无需删除Go语句。

答案 5 :(得分:1)

如另一个答案所述,不支持GO

您可以使用String.Split()语句作为分隔符在脚本上使用GO,并将每个段作为命令单独运行。

答案 6 :(得分:1)

string[] commands = sql.Split( 
    new string[]{"GO\r\n", "GO ", "GO\t"}, StringSplitOptions.RemoveEmptyEntries );
foreach (string c in commands)
{
    command = new SqlCommand(c, masterConnection);
    command.ExecuteNonQuery();
}
}
catch (Exception e)
{
    MessageBox.Show(e.Message);
}
finally
{
    masterConnection.Close();
}
}

在这里找到。 http://blogs.msdn.com/b/onoj/archive/2008/02/26/incorrect-syntax-near-go-sqlcommand-executenonquery.aspx

答案 7 :(得分:0)

最佳答案有误。 我刚测试了一个可行的解决方案 你应该留空间,';'或GO之前的新行

            var scripts = Regex.Split(statementText, @"(\s+|;|\n|\r)GO", RegexOptions.Multiline);
            foreach(var splitScript in scripts.Where(splitScript => !splitScript.IsNullOrWhiteSpace())) {
                cmd.CommandText = splitScript;
                cmd.ExecuteNonQuery();
            }

答案 8 :(得分:0)

“ iamkrillin”的答案还有1点,它使用旧的DLL使其起作用。

将引用添加到这些DLL后

  

Microsoft.SqlServer.ConnectionInfo.dll,   Microsoft.SqlServer.Management.Sdk.Sfc.dll   Microsoft.SqlServer.Smo.dll,   Microsoft.SqlServer.SqlEnum.dll

在这样的地方:“ C:\ Program Files(x86)\ Microsoft SQL Server \ 130 \ SDK \ Assemblies \ Microsoft.SqlServer.ConnectionInfo.dll” 在项目中,我需要在代码文件的顶部添加以下“ using”指令:

wmic baseboard get serialnumber

答案 9 :(得分:0)

在FluentMigrator库中有一个非常漂亮的 SqlServerBatchParser

支持GO GO 3条语句。

您需要安装 FluentMigrator.Runner.SqlServer nuget软件包

从FluentMigrator源代码大量复制(略作修改)的示例:

using FluentMigrator.Runner.BatchParser;
using FluentMigrator.Runner.BatchParser.SpecialTokenSearchers;
using FluentMigrator.Runner.BatchParser.Sources;

void Main()
{
    var connString = "Server=.;Database=mydb;Trusted_Connection=True;";
    var sql = @"select 1;
GO
SELECT 2;
GO 5";
    ExecuteBatchNonQuery(connString, sql);
}

public static void ExecuteBatchNonQuery(string ConnectionString, string sql)
{
    var sqlBatch = string.Empty;
    var conn = new SqlConnection(ConnectionString);
    conn.Open();

    try
    {
        var parser = new SqlServerBatchParser();
        parser.SqlText += (sender, args) => { sqlBatch = args.SqlText.Trim(); };
        parser.SpecialToken += (sender, args) =>
        {
            if (string.IsNullOrEmpty(sqlBatch))
                return;

            if (args.Opaque is GoSearcher.GoSearcherParameters goParams)
            {
                using (var command = conn.CreateCommand())
                {
                    command.CommandText = sqlBatch;

                    for (var i = 0; i != goParams.Count; ++i)
                    {
                        command.ExecuteNonQuery();
                    }
                }
            }

            sqlBatch = null;
        };

        using (var source = new TextReaderSource(new StringReader(sql), true))
        {
            parser.Process(source, stripComments: true);
        }

        if (!string.IsNullOrEmpty(sqlBatch))
        {
            using (var command = conn.CreateCommand())
            {
                command.CommandText = sqlBatch;
                command.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
        using (var message = new StringWriter())
        {
            message.WriteLine("An error occured executing the following sql:");
            message.WriteLine(string.IsNullOrEmpty(sqlBatch) ? sql : sqlBatch);
            message.WriteLine("The error was {0}", ex.Message);

            throw new Exception(message.ToString(), ex);
        }
    }
    finally
    {
        conn?.Dispose();
    }
}

积分:https://github.com/fluentmigrator/fluentmigrator/blob/v3.2.1/src/FluentMigrator.Runner.SqlServer/Processors/SqlServer/SqlServerProcessor.cs

答案 10 :(得分:0)

只需将“ GO”替换为“”即可。

SqlCommand command = new SqlCommand(script.Replace("GO", ""), connection);
command.CommandType = CommandType.Text;
command.ExecuteNonQuery();