'CREATE VIEW'必须是查询批处理中的第一个语句

1 c# t-sql sql-server view

这是我的脚本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)
Run Code Online (Sandbox Code Playgroud)

出现错误:

消息111,级别15,状态1,行
1'CREATE VIEW'必须是查询批处理中的第一个语句.

请帮我.

Mar*_*ell 5

这个信息不言而喻; 的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
Run Code Online (Sandbox Code Playgroud)

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

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