CREATE OR REPLACE VIEW
似乎在SQL Server中不起作用。那么如何移植CREATE OR REPLACE VIEW
来处理SQL Server?
这就是我要做的事情:
CREATE OR REPLACE VIEW data_VVVV AS
SELECT
VCV.xxxx,
VCV.yyyy AS yyyy,
VCV.zzzz AS zzzz
FROM
TABLE_A
;
有什么想法吗?
答案 0 :(得分:61)
借用@Khan的回答,我会这样做:
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
答案 1 :(得分:38)
这是另一种方法,您无需复制视图的内容:
IF (NOT EXISTS (SELECT 1 FROM sys.views WHERE name = 'data_VVV'))
BEGIN
EXECUTE('CREATE VIEW data_VVVV as SELECT 1 as t');
END;
GO
ALTER VIEW data_VVVV AS
SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A ;
首先检查视图的存在(还有其他方法可以做到这一点)。如果它不存在,那么用简单和愚蠢的东西创建它。如果是,则转到alter view
语句。
答案 2 :(得分:24)
答案 3 :(得分:13)
编辑:虽然此问题已被标记为重复,但它仍然受到关注。 @JaKXz提供的答案是正确的,应该是接受的答案。
您需要检查视图是否存在。然后根据结果执行CREATE VIEW
或ALTER VIEW
。
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
答案 4 :(得分:8)
接受的解决方案存在需要两次维护相同语句的问题,它不是非常有效(尽管它有效)。从理论上讲,Gordon Linoff的解决方案将会解决,除非它在MSSQL中不起作用,因为创建视图必须是批处理中的第一行。
drop / create不回答提出的问题。 以下是原始问题的工作。
if not exists (select * from sysobjects where name='TABLE_A' and xtype='V')
exec ('create view SELECT
VCV.xxxx,
VCV.yyyy AS yyyy,
VCV.zzzz AS zzzz
FROM TABLE_A')
答案 5 :(得分:3)
这样的事情怎么样,评论应该解释:
--DJ - 2015-07-15 Example for view CREATE or REPLACE
--Replace with schema and view names
DECLARE @viewName NVARCHAR(30)= 'T';
DECLARE @schemaName NVARCHAR(30)= 'dbo';
--Leave this section as-is
BEGIN TRY
DECLARE @view AS NVARCHAR(100) = '
CREATE VIEW ' + @schemaName + '.' + @viewName + ' AS SELECT '''' AS [1]';
EXEC sp_executesql
@view;
END TRY
BEGIN CATCH
PRINT 'View already exists';
END CATCH;
GO
--Put full select statement here after modifying the view & schema name appropriately
ALTER VIEW [dbo].[T]
AS
SELECT '' AS [2];
GO
--Verify results with select statement against the view
SELECT *
FROM [T];
干杯 -DJ
答案 6 :(得分:0)
可以通过删除视图并重新创建视图来完成视图的更改。使用以下内容删除并重新创建视图。
IF EXISTS
(SELECT NAME FROM SYS.VIEWS WHERE NAME = 'dbo.test_abc_def')
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
答案 7 :(得分:-1)
IF NOT EXISTS(select * FROM sys.views where name = 'data_VVVV ')
BEGIN
CREATE VIEW data_VVVV AS
SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
END
ELSE
BEGIN
ALTER VIEW data_VVVV AS
SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A VCV
END