这个SQL代码在SMMS中执行时有效,但在.Net中通过ExecuteNonQuery()调用时却不行吗?

时间:2013-10-08 12:20:55

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

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

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内的文件夹中,然后我生成了以下片段:

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,但通常应该在每个GO之前的CREATE VIEW之前消除,此消息似乎也表明它不喜欢WITH SCHEMABINDING,但是究竟是为什么?

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

感谢。

1 个答案:

答案 0 :(得分:4)

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

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

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