【问题标题】:This SQL code works when being executed in SMMS but not when called via ExecuteNonQuery() in .Net why?此 SQL 代码在 SMMS 中执行时有效,但在 .Net 中通过 ExecuteNonQuery() 调用时无效,为什么?
【发布时间】:2013-10-08 12:20:54
【问题描述】:

我想这是一件很小的事情,但我似乎没有看到。 我有一个脚本可以在已经存在的数据库中设置一些视图和索引(列和表的详细信息对于这个问题应该无关紧要......)

USE <dbname>

GO
CREATE VIEW [dbo].View1_
WITH SCHEMABINDING
AS
  SELECT
      [someTable].[Id]
  FROM [dbo].[someTable]
  WHERE [dbo].[someTable].[Str] != N'someString'

GO
CREATE UNIQUE CLUSTERED INDEX someTable_Index1
    ON [dbo].View1_(ID)

GO
...

例如,如果我从 SQL Server Management Studio 运行它,现在它执行得很好。 但是我希望在调用某个网站时进行设置;我将上面的脚本保存在 MVC4-Project 内的文件夹中,并生成了以下 sn-p:

string connectionString = ConfigurationManager.ConnectionStrings["SomeConnectionString"].ToString();

string scriptCommand = System.IO.File.ReadAllText(Server.MapPath("~/Models/View1_IndexedViews.sql"));

using(SqlConnection connection = new SqlConnection(connectionString))
{
    using (SqlCommand command = connection.CreateCommand())
    {
        connection.Open();
        command.CommandText = scriptCommand;

        try
        {
            command.ExecuteNonQuery();
        }
        catch(SqlException e)
        {

        }
    }

}

但是现在当我触发那个调用时,这里会抛出一个异常

"Incorrect syntax near 'GO'.\r\n'CREATE VIEW' must be the first statement in a query batch.\r\nIncorrect 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.

有人可以给我一个提示,我在这里缺少什么吗?我知道那条消息CREATE VIEW must be the first statement,但通常应该在每个CREATE VIEW 之前加上GOs 来消除它,这条消息似乎也表明它不喜欢WITH SCHEMABINDING,但为什么会这样呢?

任何提示/帮助表示赞赏!

谢谢。

【问题讨论】:

    标签: .net sql sql-server asp.net-mvc-4


    【解决方案1】:

    该数据库没有任何go 命令,仅在Management Studio(和一些类似工具)中用于分隔批次。

    在某些情况下,您可以删除 go 命令并将其作为单个批处理运行。否则,您需要将它们分成几个数据库调用。

    如果语法与示例中一样可预测,那么您可以在 "\r\nGO\r\n" 上拆分并执行每个字符串。

    【讨论】:

    • 好点,还不知道GO,这里是参考technet.microsoft.com/en-us/library/ms188037.aspx,所以如果我想批量创建多个视图,我必须将其拆分,对吗?
    • 啊刚刚阅读了您关于按GO 拆分的编辑,非常好的输入,谢谢!
    猜你喜欢
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 2015-02-01
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 2021-08-16
    相关资源
    最近更新 更多