How to check if a view exists before having it created?

0

Take the following view as an example:

CREATE VIEW vw_types AS
SELECT
    codigo AS code,
    nome AS description,
    abreviacao AS abbreviation,
    statusRegistro AS status
FROM 
    tipos

How can I have it created only if it does not exist in the database?

    
asked by anonymous 24.02.2015 / 14:14

1 answer

1

If you do not want to change or delete the View that already exists, just check if it exists, if there is any action or do nothing.

      IF NOT EXISTS (
        SELECT * FROM sys.views v
        INNER JOIN sys.schemas s on v.schema_id = s.schema_id
        WHERE s.name = 'dbo' and v.name = 'vw_types'
    )
        EXEC sp_executesql @statement = N'CREATE VIEW vw_types AS
SELECT
    codigo AS code,
    nome AS description,
    abreviacao AS abbreviation,
    statusRegistro AS status
FROM 
    tipos;' ;
ELSE
        print 'ja exixte uma view com esse nome'
GO

In this case I'm just bringing a message that it already exists in ELSE print 'ja exixte uma view com esse nome' , but this is optional. You can delete, or have another action taken.

    
24.02.2015 / 14:56