Answers:
上面的解决方案虽然可以完成工作,但是这样做有可能会丢失用户权限。我更喜欢如下创建或替换视图或存储过程。
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_myView]'))
EXEC sp_executesql N'CREATE VIEW [dbo].[vw_myView] AS SELECT ''This is a code stub which will be replaced by an Alter Statement'' as [code_stub]'
GO
ALTER VIEW [dbo].[vw_myView]
AS
SELECT 'This is a code which should be replaced by the real code for your view' as [real_code]
GO
作为参考,SQL Server 2016 SP1+
您可以使用CREATE OR ALTER VIEW
语法。
CREATE [ OR ALTER ] VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ] [ WITH <view_attribute> [ ,...n ] ] AS select_statement [ WITH CHECK OPTION ] [ ; ]
或更改
仅在视图已经存在时有条件地对其进行更改。
我用:
IF OBJECT_ID('[dbo].[myView]') IS NOT NULL
DROP VIEW [dbo].[myView]
GO
CREATE VIEW [dbo].[myView]
AS
...
最近,我为此类内容添加了一些实用程序:
CREATE PROCEDURE dbo.DropView
@ASchema VARCHAR(100),
@AView VARCHAR(100)
AS
BEGIN
DECLARE @sql VARCHAR(1000);
IF OBJECT_ID('[' + @ASchema + '].[' + @AView + ']') IS NOT NULL
BEGIN
SET @sql = 'DROP VIEW ' + '[' + @ASchema + '].[' + @AView + '] ';
EXEC(@sql);
END
END
所以现在我写
EXEC dbo.DropView 'mySchema', 'myView'
GO
CREATE View myView
...
GO
我认为这使我的变更脚本更具可读性
它在SQL Server 2017上对我来说很好用:
USE MSSQLTipsDemo
GO
CREATE OR ALTER PROC CreateOrAlterDemo
AS
BEGIN
SELECT TOP 10 * FROM [dbo].[CountryInfoNew]
END
GO
https://www.mssqltips.com/sqlservertip/4640/new-create-or-alter-statement-in-
在SQL Server 2016(或更高版本)中,可以使用以下命令:
CREATE OR ALTER VIEW VW_NAMEOFVIEW AS ...
在旧版本的SQL Server中,您必须使用类似
DECLARE @script NVARCHAR(MAX) = N'VIEW [dbo].[VW_NAMEOFVIEW] AS ...';
IF NOT EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')
-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL
BEGIN EXEC('CREATE ' + @script) END
ELSE
BEGIN EXEC('ALTER ' + @script) END
或者,如果视图上没有依赖项,则可以将其删除并重新创建:
IF EXISTS(SELECT * FROM sys.views WHERE name = 'VW_NAMEOFVIEW')
-- IF OBJECT_ID('[dbo].[VW_NAMEOFVIEW]') IS NOT NULL
BEGIN
DROP VIEW [VW_NAMEOFVIEW];
END
CREATE VIEW [VW_NAMEOFVIEW] AS ...
CREATE OR REPLACE VIEW
语法。正确的语法是CREATE OR ALTER VIEW
。怎么来了,这everybdody指出它是CREATE OR REPLACE
在所有其他SO线程我发现🤔