& # 39;创建视图# 39;必须是查询批处理中的第一条语句

本文关键字:语句 批处理 一条 视图 创建 查询 | 更新日期: 2023-09-27 18:18:55

这是我在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'必须是查询批处理中的第一个语句。

请帮帮我。

& # 39;创建视图# 39;必须是查询批处理中的第一条语句

消息不言自明;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...');

把它分成两个脚本,先运行

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

然后剩下的