2016年5月30日 星期一

[DB]How to make CREATE OR REPLACE VIEW work in SQL Server?

在Oracle的環境下,如果要修改View的內容可以使用CREATE OR REPLACE VIEW來處理
CREATE OR REPLACE VIEW data_VVVV AS 
SELECT 
    VCV.xxxx,
        VCV.yyyy AS yyyy,
        VCV.zzzz AS zzzz
FROM 
TABLE_A
;
但是MS SQL下無法這樣做
要處理以下的問題可使用
1.
IF OBJECT_ID('dbo.data_VVVV') IS NULL
BEGIN
    CREATE VIEW dbo.data_VVVV
    AS
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
END
ELSE
    ALTER VIEW dbo.data_VVVV
    AS
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
BEGIN
END
or
2.
IF OBJECT_ID('dbo.test_abc_def', 'V') IS NOT NULL
    DROP VIEW dbo.test_abc_def
GO

CREATE VIEW dbo.test_abc_def AS
SELECT 
    VCV.xxxx
    ,VCV.yyyy AS yyyy
    ,VCV.zzzz AS zzzz
FROM TABLE_A
如果要判斷這個View是否存在
還有別的用法,如:
IF (NOT EXISTS (SELECT 1 FROM sys.views WHERE name = 'data_VVV'))
if not exists (select * from sysobjects where name='data_VVV' and xtype='V')
剩下就看你要Drop重建或是Alter View

沒有留言:

張貼留言