使用存在检查创建视图

时间:2016-11-30 16:39:26

标签: sql sql-server

我试图这样做:

IF NOT EXISTS (
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[viewName]')
AND type in (N'U')
)

CREATE VIEW [dbo].[viewName] AS
-- Such and such
GO

这会抛出"'创建视图'必须是批次中的唯一声明"错误。

我已尝试过here(围绕BEGIN / END)和here(使用GO语句,使用动态SQL)的建议,但没有人减轻错误。

3 个答案:

答案 0 :(得分:1)

尝试这个逻辑,你的有点偏;

echo "Initializing the master node"
kubeadm reset
systemctl start kubelet.service
kubeadm init

我说实话,我总是放弃并重新创建,以确保您运行最新版本的视图,就像这样;

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE object_id= object_id(N'[dbo].[ViewName]') AND OBJECTPROPERTY(object_id, N'IsView') = 1)

是的,所以检查你想要使用动态SQL的评论;

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE object_id= object_id(N'[dbo].[ViewName]') AND OBJECTPROPERTY(object_id, N'IsView') = 1)
BEGIN
    DROP VIEW [dbo].ViewName
END
GO

CREATE VIEW ViewName
AS
    SELECT 

答案 1 :(得分:1)

可能是这样的:

DECLARE @cmd NVARCHAR(MAX)=N'CREATE VIEW ....;';

IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.VIEWS AS v WHERE v.TABLE_NAME='ViewName') --yes, it's TABLE_NAME!
    SET @cmd=STUFF(@cmd,1,6,N'ALTER');

EXEC(@cmd);

答案 2 :(得分:0)

您目前不太可能正在使用SQL 2016 SP1,但对于子孙后代,您现在可以

CREATE OR ALTER VIEW ... https://stackoverflow.com/a/40707436/155892