如何检查视图是否存在,如果不存在则创建

时间:2018-03-07 09:23:58

标签: sql sql-server ssms sql-server-2016

我想在SQL Server 2016中创建一个视图

IF EXISTS(SELECT 1 FROM sys.views 
     WHERE Name = 'VI_ALL_CITIES_AS_CATEGORY')
BEGIN
CREATE VIEW VI_ALL_CITIES_AS_CATEGORY AS
    SELECT PERSONS.FIRST_NAME AS 'Име', PERSONS.LAST_NAME AS 'Фамилия', CITIES.CITY_NAME AS 'Град'
    FROM CITIES
    LEFT JOIN PERSONS ON CITIES.ID = PERSONS.CITY_ID ;
END

但它给了我错误:

  

语法错误:'创建视图'必须是该中唯一的陈述   批次。

2 个答案:

答案 0 :(得分:2)

尝试这种方法

IF NOT EXISTS
(
    SELECT 1
    FROM sys.views
    WHERE Name = 'VI_ALL_CITIES_AS_CATEGORY'
)
BEGIN

    EXEC('CREATE VIEW VI_ALL_CITIES_AS_CATEGORY AS SELECT 1 as Val')

END
GO

ALTER VIEW VI_ALL_CITIES_AS_CATEGORY
AS
SELECT 
    PERSONS.FIRST_NAME AS 'Име',
    PERSONS.LAST_NAME AS 'Фамилия',
    CITIES.CITY_NAME AS 'Град'
    FROM CITIES
       LEFT JOIN PERSONS 
          ON CITIES.ID = PERSONS.CITY_ID

答案 1 :(得分:1)

您有两个选择:

1)如果您正在使用SSMS或任何可以将脚本拆分为不同批次的客户端:

IF EXISTS(SELECT 'view exists' FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = N'YourViewName'AND TABLE_SCHEMA = 'YourViewSchema')
BEGIN
    DROP VIEW YourViewSchema.YourViewName
END

GO -- This will make the next statement the first in it's batch

CREATE VIEW YourViewSchema.YourViewName AS
SELECT something = 1
FROM YourTable

GO

2)如果您无法将代码分成批次,则必须使用动态SQL“欺骗”引擎来创建视图:

 IF NOT EXISTS(SELECT 'view exists' FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = N'YourViewName'AND TABLE_SCHEMA = 'YourViewSchema')
    BEGIN
        DECLARE @v_ViewCreateStatement VARCHAR(MAX) = '
            CREATE VIEW YourViewSchema.YourViewName AS
                SELECT something = 1
                FROM YourTable'

        EXEC (@v_ViewCreateStatement)

    END

请注意,1)是IF EXISTS,而2)是IF NOT EXISTS

原因是大多数DDL语句需要在批处理中排在第一位,所以不幸的是,你不能在其他语句之后放置CREATE对象语句。