2016-03-21 66 views
14

我有脚本,我想先放下视图然后创建它。 我知道如何删除表:删除视图(如果存在)

IF EXISTS (SELECT * FROM sys.tables WHERE name = 'table1' AND type = 'U') DROP TABLE table1; 

,所以我也做了同样的观点:

IF EXISTS (SELECT * FROM sys.views WHERE name = 'view1' AND type = 'U') DROP VIEW view1; 
create view1 as(......) 

,然后我得到了错误:

'CREATE VIEW' must be the first statement in a query batch.

+1

在这些命令之间放置一个'GO' ... – Shnugo

+0

我在创建之前放入:Go Create ....等等,但是然后得到:数据库中已经有一个名为'TSB'的对象。 – 4est

+3

错误的对象类型 - 使用'V'而不是'U'。 https://msdn.microsoft.com/en-us/library/ms190324.aspx –

回答

42

你的存在语法错误,你应该像下面那样单独使用DDL

if exists(select 1 from sys.views where name='tst' and type='v') 
drop view tst; 
go 

create view tst 
as 
select * from test 

您还可以检查是否存在测试,与OBJECT_ID像下面

if object_id('tst','v') is not null 
drop view tst; 
go 

create view tst 
as 
select * from test 

在SQL 2016年,您可以使用下面的语法下降

Drop view if exists dbo.tst 

从SQL2016 CU1,你可以做以下

create or alter view vwTest 
as 
select 1 as col; 
go 
+2

谢谢,改变U到V,现在正在工作!感谢您的帮助 – 4est

+1

小修正 - DROP VIEW dbo.tst如果EXISTS应该读取DROP VIEW如果存在dbo.tst – Rich

+0

@Rich:感谢您的纠正,我现在更新 – TheGameiswar