服务器之家:专注于服务器技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Sql Server - SQL SERVER先判断视图是否存在然后再创建视图的语句

SQL SERVER先判断视图是否存在然后再创建视图的语句

2020-04-05 15:05whsnow Sql Server

SQL SERVER中先判断视图是否存在,使用IF NOT EXISTS,然后再创建视图,使用create view,整个过程如下

如果我们的语句为:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
IF NOT EXISTS(SELECT 1 FROM sys.views WHERE name='Report_IndividualTicket')
BEGIN
create view Report_IndividualTicket
as
SELECT Ticket.TicketNumber, Ticket.TicketID,
GisProcess.StageName,
Content.DtReceived, Content.ContentText
FROM
(GisProcess INNER JOIN Ticket
ON GisProcess.TicketID=Ticket.TicketID)
INNER JOIN Content
ON Ticket.ContentID=Content.ContentID
END

会提示以下错误:

Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'view'.

出现这个错误的原因是:create view 这一句必须是批处理中的第一句。

所以可以将该语句修改为:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
IF EXISTS(SELECT 1 FROM sys.views WHERE name='Report_IndividualTicket')
DROP VIEW Report_IndividualTicket
GO
create view Report_IndividualTicket
as
SELECT Ticket.TicketNumber, Ticket.TicketID,
GisProcess.StageName,
Content.DtReceived, Content.ContentText
FROM
(GisProcess INNER JOIN Ticket
ON GisProcess.TicketID=Ticket.TicketID)
INNER JOIN Content
ON Ticket.ContentID=Content.ContentID
GO

 

延伸 · 阅读

精彩推荐