删除视图(如果存在)

4es*_*est 28 sql sql-server view create-view

我有脚本,我想首先删除视图,然后创建它.我知道如何放桌子:

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

所以我对观点做了同样的事情:

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

然后我得到了错误:

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

The*_*war 77

你存在的语法是错误的,你应该用下面的方式分离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
Run Code Online (Sandbox Code Playgroud)

你也可以用object_id检查存在测试,如下所示

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

create view tst
as
select * from test
Run Code Online (Sandbox Code Playgroud)

在SQL 2016中,您可以使用以下语法删除

Drop view  if exists dbo.tst
Run Code Online (Sandbox Code Playgroud)

从SQL2016 CU1,您可以在下面执行

create or alter view vwTest
as
 select 1 as col;
go
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,将U改为V,现在正在工作!感谢帮助 (2认同)

Anw*_*Haq 5

DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS 
SELECT * from {TableName}  
Go
Run Code Online (Sandbox Code Playgroud)