SQL Server equivalent to Oracle's CREATE OR REPLACE VIEW

后端 未结 9 1740
猫巷女王i
猫巷女王i 2020-12-02 10:24

In Oracle, I can re-create a view with a single statement, as shown here:

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


        
相关标签:
9条回答
  • 2020-12-02 11:03

    For reference from SQL Server 2016 SP1+ you could use CREATE OR ALTER VIEW syntax.

    MSDN CREATE VIEW:

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

    OR ALTER

    Conditionally alters the view only if it already exists.

    db<>fiddle demo

    0 讨论(0)
  • 2020-12-02 11:05

    You can use ALTER to update a view, but this is different than the Oracle command since it only works if the view already exists. Probably better off with DaveK's answer since that will always work.

    0 讨论(0)
  • 2020-12-02 11:07

    The solutions above though they will get the job done do so at the risk of dropping user permissions. I prefer to do my create or replace views or stored procedures as follows.

    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
    
    0 讨论(0)
提交回复
热议问题