【问题标题】:Executing SQL code [duplicate]执行 SQL 代码 [重复]
【发布时间】:2015-07-11 09:18:38
【问题描述】:

我有创建数据库和表的脚本(大约 50 个表)。当我将脚本复制粘贴到 SQL 管理工作室时,它运行良好,但是当我尝试从我的应用程序运行时,我收到了 SQL 异常。

这是我的代码:

string enterRecordsScript = "my sql script";
SqlCommand enterRecords = new SqlCommand(enterRecordsScript, connection);
enterRecords.ExecuteNonQuery();

这里是个例外:

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'GO'.
'CREATE VIEW' must be the first statement in a query batch.
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
Incorrect syntax near 'GO'.

这是脚本:

CREATE DATABASE TEST3
GO
USE Test3;

CREATE TABLE [SAShoppingInvoice]
(
    [Guid] uniqueidentifier PRIMARY KEY NOT NULL ROWGUIDCOL,
    [Number] nvarchar(50),
    [DateOfShopping] datetime,
    [SubTotal] decimal(18,2) DEFAULT 0,
    [PSubTotal] decimal(18,2) DEFAULT 0,
    [Freight] decimal(18,2) DEFAULT 0,
    [Total] decimal(18,2) DEFAULT 0,
    [ATotal] decimal(18,2) DEFAULT 0,
    [PriceLevel] nvarchar(20),
    [SummaryTotal] decimal(18,2) DEFAULT 0,
);


CREATE TABLE [SAShoppingInvoiceDetail]
(
    [Guid] uniqueidentifier PRIMARY KEY NOT NULL ROWGUIDCOL,
    [Number] nvarchar(50),
    [UnitPrice] decimal(18,2) DEFAULT 0,
    [Quantity] decimal(18,2) DEFAULT 0,
    [Description] nvarchar(100),
);



ALTER TABLE [SAShoppingInvoiceDetail]
ADD ShoppingInvoiceGuid uniqueidentifier
CONSTRAINT FK_SAShoppingInvoice_ShoppingInvoice_To_SAShoppingInvoiceDetail_ShoppingInvoice
FOREIGN KEY (ShoppingInvoiceGuid) 
REFERENCES [SAShoppingInvoice](Guid);

GO
CREATE VIEW SAShoppingInvoice_SummaryTotal WITH SCHEMABINDING AS SELECT ShoppingInvoiceGuid,  SUM(ISNULL(Quantity,0)*ISNULL(UnitPrice,0)) as SummaryTotal, COUNT_BIG(*) as CountBig
FROM dbo.SAShoppingInvoiceDetail Group By ShoppingInvoiceGuid;
GO
CREATE UNIQUE CLUSTERED INDEX idx_SAShoppingInvoiceSummaryTotal ON SAShoppingInvoice_SummaryTotal(ShoppingInvoiceGuid);

为什么从我的应用程序运行脚本会出现问题?

【问题讨论】:

  • 您必须共享 sql 脚本。
  • 就像说CREATE VIEW 必须是查询批处理中的第一条语句。意味着您应该在CREATE VIEW 语句之前使用Go 声明
  • @faridbekran 不,包含GO 的事实是问题所在。在其中添加更多 GOs 不会解决任何问题。

标签: c# sql sql-server


【解决方案1】:

GO 不是有效的 SQL。某些特定工具(例如 SSMS)使用它来将大型文本文件拆分为多个单独的命令。在您自己的程序中,这成为您的责任。

如果你有一个文本文件

一个
去
b
去
C
去

那么如果你想使用SqlCommand对象来执行这个,你需要三个命令,一个包含a,一个包含b,一个包含c。这三个都不包括GO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 2023-04-10
    • 1970-01-01
    • 2022-06-25
    • 1970-01-01
    相关资源
    最近更新 更多