2016-03-21 64 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