You have 2 options:
1) If you are using SSMS or any client that can split your script into different batches:
IF EXISTS(SELECT 'view exists' FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = N'YourViewName'AND TABLE_SCHEMA = 'YourViewSchema')
BEGIN
DROP VIEW YourViewSchema.YourViewName
END
GO -- This will make the next statement the first in it's batch
CREATE VIEW YourViewSchema.YourViewName AS
SELECT something = 1
FROM YourTable
GO
2) If you can't split code into batches, you will have to "fool" the engine using dynamic SQL to create your view:
IF NOT EXISTS(SELECT 'view exists' FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_NAME = N'YourViewName'AND TABLE_SCHEMA = 'YourViewSchema')
BEGIN
DECLARE @v_ViewCreateStatement VARCHAR(MAX) = '
CREATE VIEW YourViewSchema.YourViewName AS
SELECT something = 1
FROM YourTable'
EXEC (@v_ViewCreateStatement)
END
Note that 1) is an IF EXISTS
and 2) is an IF NOT EXISTS
.
The reason for this is that most DDL statements need to be first in a batch, so you can't put CREATE
object statements after other statements, unfortunately.