在Oracle中,我可以使用单个语句重新创建一个视图,如下所示:
CREATE OR REPLACE VIEW MY_VIEW AS
SELECT SOME_FIELD
FROM SOME_TABLE
WHERE SOME_CONDITIONS
正如语法所暗示的那样,这将删除旧视图并使用我给出的任何定义重新创建它。
在MSSQL(SQL Server 2005或更高版本)中是否有相同的东西可以做同样的事情?
答案 0 :(得分:99)
上述解决方案虽然可以完成工作,但却有可能降低用户权限。我更喜欢按如下方式创建或替换视图或存储过程。
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
答案 1 :(得分:44)
您可以使用'IF EXISTS'来检查视图是否存在,如果存在则丢弃。
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = 'MyView') DROP VIEW MyView GO CREATE VIEW MyView AS .... GO
答案 2 :(得分:26)
有关 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 ] [ ; ]
或更改
只有在视图已存在的情况下才有条件地改变视图。
<强> db<>fiddle demo 强>
答案 3 :(得分:13)
我用:
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
我认为它使我的更改脚本更具可读性
答案 4 :(得分:6)
我通常使用这样的东西:
if exists (select * from dbo.sysobjects
where id = object_id(N'dbo.MyView') and
OBJECTPROPERTY(id, N'IsView') = 1)
drop view dbo.MyView
go
create view dbo.MyView [...]
答案 5 :(得分:5)
答案 6 :(得分:2)
您可以使用ALTER更新视图,但这与Oracle命令不同,因为它仅在视图已存在时才有效。可能会有更好的与DaveK的回答,因为这将始终有效。
答案 7 :(得分:2)
在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-
答案 8 :(得分:1)
在SQL Server 2016(或更高版本)中,您可以使用此代码:
CREATE OR REPLACE 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