tags:

views:

7880

answers:

4

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_CONDITIONS

As the syntax implies, this will drop the old view and re-create it with whatever definition I've given.

Is there an equivalent in SQL Server 2005 that will do the same thing?

+9  A: 

You can use 'IF EXISTS' to check if the view exists and drop if it does.

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

CREATE VIEW MyView
AS 
     ....
GO
DaveK
That's the way I do it too. Oracle's Create or replace is way better, I hate to repeat code.
Rismo
+3  A: 

I typically use something like this:

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 [...]
Michael Petrotta
This also works with stored procedures, tables, etc.
Dave
A: 

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.

Bryant
Although ALTER keeps existing Permissions (and retains the Old Version if the new version has syntax errors etc.). So using IF NOT EXISTS ... to create a Stub, and then ALTER to replace it/original may be better in maintaining permissions and dependencies.
Kristen
+3  A: 

I use:

IF OBJECT_ID('[dbo].[myView]') IS NOT NULL
DROP VIEW [dbo].[myView]
GO
CREATE VIEW [dbo].[myView]
AS

...

Recently I added some utility procedures for this kind of stuff:

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

So now I write

EXEC dbo.DropView 'mySchema', 'myView'
GO
CREATE View myView
...
GO

I think it makes my changescripts a bit more readable

Tom