Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

CREATE OR REPLACE VIEW doesn't seem to work in SQL Server. So how do I port CREATE OR REPLACE VIEW to work on SQL Server?

This is what I'm trying to do:

CREATE OR REPLACE VIEW data_VVVV AS  SELECT      VCV.xxxx,         VCV.yyyy AS yyyy,         VCV.zzzz AS zzzz FROM  TABLE_A ; 

Any ideas?

like image 976
Alexander Kalian Avatar asked Aug 30 '13 14:08

Alexander Kalian


People also ask

How do I create a duplicate view in SQL Server?

you have to "script it out"... in SSMS select the view and rx click on it.. select the "Script as" ->"Drop and CREATE to" ->"New query window".. this will open a new query window with the exact statements to drop and re-create the view..

Can we update the views once created?

Yes we can update view, if :- if view is created on a single table - if view contains the primary key field - if view contains all the not null fields of underlying tables - if view query doesn't contain group by or any aggregated field.

What is the use of create and replace in view?

Create or replace View: These keywords serve to create or replace the existing View. When we run the create or the replace view statement, MySQL checks whether it exists in the database. If the View exists, it changes the View definition using the query specified after the AS keyword.


2 Answers

Borrowing from @Khan's answer, I would do:

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 

MSDN Reference

like image 85
JaKXz Avatar answered Oct 11 '22 06:10

JaKXz


Here is another method, where you don't have to duplicate the contents of the view:

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 ; 

The first checks for the existence of the view (there are other ways to do this). If it doesn't exist, then create it with something simple and dumb. If it does, then just move on to the alter view statement.

like image 25
Gordon Linoff Avatar answered Oct 11 '22 08:10

Gordon Linoff