创建视图作为SELECT FROM,检查表是否存在

时间:2017-07-12 14:15:06

标签: sql-server

在创建视图时,是否可以检查我选择的表实际存在?为了防止关键字视图附近的无效的对象名称' MyItems' 语法错误。

-- ok this is super simplistic
-- but it is enough to illustrate the point
CREATE VIEW vw_MyView
AS
SELECT DISTINCT Id, Name, COUNT(CategoryId) OVER (PARTITION BY Id) AS Total
FROM MyItems
GO

我有一堆这些视图是作为批处理脚本的一部分创建的。在此示例中,如果MyItems不存在,则执行会中断整个批处理脚本。

所以,我想我会在每个CREATE VIEW语句前添加一堆检查,以确保表格实际存在。

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[MyItems]') AND type IN (N'U'))
    -- CREATE VIEW <snip></snip>
GO

但事实证明,CREATE VIEW语句必须是查询批处理中的第一个语句。

回到我的问题,当CREATE VIEW无法完成时,是否存在某种解决方法,因为它是从现有的表中读取的?

我正在使用MS SQL Server 2008 R2。

2 个答案:

答案 0 :(得分:1)

使用动态SQL的另一种选择:

DECLARE @sqlcmd NVARCHAR(MAX);

SELECT @sqlcmd = 
'CREATE VIEW vw_MyView
 AS
 SELECT DISTINCT Id, Name, COUNT(CategoryId) OVER (PARTITION BY Id) AS Total
 FROM MyItems
 GO';

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[MyItems]') AND type IN (N'U'))
  BEGIN
    EXEC sp_executesql @sqlcmd
  END

ELSE
  BEGIN 
    PRINT 'Table doesnt exist'
  END

答案 1 :(得分:0)

此代码可以帮助您,尝试一次

IF EXISTS (
        SELECT 1
        FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_NAME = 'MyItems'
            AND TABLE_TYPE = 'BASE TABLE'
        )
BEGIN
    IF NOT EXISTS (
            SELECT 1
            FROM INFORMATION_SCHEMA.TABLES
            WHERE TABLE_NAME = 'vw_MyView'
                AND TABLE_TYPE = 'VIEW'
            )
    BEGIN
        CREATE VIEW vw_MyView
        AS
        SELECT DISTINCT Id
            ,NAME
            ,COUNT(CategoryId) OVER (PARTITION BY Id) AS Total
        FROM MyItems 
    END 
END