Skip to content

ViewExists

Steven Liekens edited this page Aug 26, 2016 · 2 revisions

Syntax

dbo.ViewExists( 'name' )

Arguments

name
sysname, required
The name of a view, optionally qualified with a schema name. When a schema name is specified, only views in that schema are searched.

Return Types

bit, not null
A value indicating whether a view with the specified name and optional schema exists, or NULL if the format of name is invalid.

Usage Examples

Note that you can't use CREATE VIEW or ALTER VIEW inside a conditional block. You can use sp_executesql as a workaround. The following example uses sp_executesql to ensure that a placeholder view with the specified name exists. You can then use ALTER VIEW on the placeholder view in a new batch.

-- Create a placeholder that can be altered later
IF dbo.ViewExists('dbo.ProductAndDescription') = 0
  EXEC sp_executesql @statements = N'CREATE VIEW dbo.ProductAndDescription AS SELECT NULL [undefined]'
GO

ALTER VIEW dbo.ProductAndDescription
AS -- Actual implementation
SELECT ...

The same restrictions do not apply to DROP VIEW.

IF dbo.ViewExists('ProductAndDescription') = 1
  DROP VIEW ProductAndDescription;
Clone this wiki locally