【问题标题】:'CREATE VIEW' must be the first statement in a query batch'CREATE VIEW' 必须是查询批处理中的第一条语句
【发布时间】:2013-06-18 09:01:14
【问题描述】:

这是我在C# 中的脚本:

exec sp_executesql N'
IF OBJECT_ID(N''RealEstate.vwContract'', N''V'') IS NOT NULL
  DROP VIEW RealEstate.vwContract

CREATE VIEW RealEstate.vwContract
AS
  SELECT RealEstate.Contract.ID .... (Rest of Statement omitted for brevity)

出现错误:

消息 111,第 15 级,状态 1,第 1 行
“CREATE VIEW”必须是查询批处理中的第一条语句。

请帮帮我。

【问题讨论】:

  • 删除视图后不需要GO 吗?
  • 我测试了这个解决方案,但它显示:'GO' 附近的语法不正确
  • @Simin.D.Karbasi 确实,GO 是 SSMS 等工具引入的善意谎言; GO 不是 SQL 语言的一部分,但被某些工具用来将单个文件拆分为多个命令

标签: c# sql-server tsql view


【解决方案1】:

信息不言自明; create view 必须是第一个语句 - 但你可以作弊。我的创建脚本(如果我需要从 ADO.NET 运行它们,所以没有GO)看起来很像:

if not exists(select 1 from sys.tables where name='SomeTable')
begin
    exec('create table SomeTable ....blah not shown');
    -- more to add indexing etc
end
if not exists(select 1 from sys.tables where name='SomeOtherTable')
begin
    exec('create table SomeOtherTable ....blah not shown');
    -- more to add indexing etc
end

你可以用sys.views 做同样的事情。也许,未经测试:

if exists (select 1 from sys.views where name = 'MyView')
    exec ('drop view MyView');
exec ('create view MyView ...blah not shown...');

【讨论】:

  • 在我看来不是最好的方法,因为编辑时没有语法检查。
  • @Artyom 只有一行跳过了语法检查,它的优点是可以轻松地重新运行 - 理想情况下你应该在开发它时这样做。
【解决方案2】:

拆分成两个脚本先运行

IF OBJECT_ID(N''RealEstate.vwContract'', N''V'') IS NOT NULL
   DROP VIEW RealEstate.vwContract

剩下的

【讨论】:

  • 如果你这样做了,那么create view 仍然不是第一次操作
  • @MarcGravell 我解释这个答案的方式是exec sp_executesql N'if ... drop view ...' exec sp_executesql N'create view ...'。即使这两个sp_executesqls 本身在同一个批次中,这也是有效的。它的功能与您在答案中使用的功能相同。
  • @hvd 这不是答案所说的,虽然
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多