Sql Server相当于Oracle的CREATE OR REPLACE VIEW

在Oracle中,我可以用一条语句重新创build一个视图,如下所示:

CREATE OR REPLACE VIEW MY_VIEW AS SELECT SOME_FIELD FROM SOME_TABLE WHERE SOME_CONDITIONS 

正如语法所暗示的,这将会抛弃旧的视图,并用我给出的任何定义重新创build视图。

在SQL Server 2005中是否有相同的function呢?

上述解决scheme虽然可以完成工作,但可能会导致用户权限下降。 我更喜欢按照以下方式创build或replace视图或存储过程。

 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 

您可以使用“IF EXISTS”来检查视图是否存在,如果存在则放弃。

 IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
         WHERE TABLE_NAME ='MyView')
     DROP VIEW MyView
走

创build视图MyView
如 
      ....
走

我用:

 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 2016 SP1+参考,您可以使用CREATE OR ALTER VIEW语法。

MSDN CREATE VIEW :

 CREATE [ OR ALTER ] VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ] [ WITH <view_attribute> [ ,...n ] ] AS select_statement [ WITH CHECK OPTION ] [ ; ] 

或者ALTER

只有在已经存在的情况下才有条件地改变视图。

我通常使用这样的东西:

 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 [...] 

从SQL Server 2016开始

 DROP TABLE IF EXISTS [foo]; 

MSDN源码

您可以使用ALTER来更新视图,但这与Oracle命令不同,因为它只在视图已经存在的情况下才起作用。 DaveK的答案可能会更好,因为这将始终有效。