Quantcast
Channel: CodeFari
Viewing all articles
Browse latest Browse all 265

How to check if a VIEW exist in SQL Server

$
0
0
Many scenario come in query writing, we have to check particular VIEW exists in database or not. There are many approach to check existing view in SQL server, some approach script described below.

For the demonstration I am creating a database "Codefari" same as table "Employee" and view "EmployeeView". Run below script.


USE[Codefari]
GO
CREATETABLEEmployee
(
       IDINTIDENTITY(1,1),
       FirstNameVARCHAR(400),
       LastNameVARCHAR(400)
)
GO
INSERTINTOEmployee
SELECT'Dilip','Singh'
UNIONALL
SELECT'Ashish','Singh'
GO
CREATEVIEWdbo.EmployeeView
AS
SELECTID,FirstName+''+LastNameASFullNameFROMEmployee
GO
SELECT*FROMdbo.EmployeeView
GO


 Using sys.view catalog
We can write a query like below to check a particular VIEW exist in current database for all schema.


USE[Codefari]
GO
IFEXISTS(SELECT 1 FROMsys.viewsWHEREName='EmployeeView')
BEGIN
       PRINT'View is exist'
END
ELSE
BEGIN
       PRINT'View is not exist'
END


Result
View is exist

Above script is responsible to check existing of view "EmployeView" for all schema in same database. If you want to check existing view for a particular schema in same database then use following script.


USE[Codefari]
GO
IFEXISTS(SELECT 1 FROMsys.viewsWHEREOBJECT_ID=OBJECT_ID('dbo.EmployeeView'))
BEGIN
       PRINT'View is exist'
END
ELSE
BEGIN
       PRINT'View is not exist'
END


Result
View is exist

Using sys.objects catalog
Using following script you can also check existing of view "EmployeeView" in database.


USE[Codefari]
GO
IFEXISTS(SELECT*FROMsys.objectsWHEREobject_id=OBJECT_ID('dbo.EmployeeView')ANDtype='V')
BEGIN
    PRINT'View is Exist'
END
ELSE
BEGIN
       PRINT'View is not exist'
END



Result
View is exist

Using sys.sql_modules catalog
We can also use sys.sql_modules catalog to check existing view "EmployeeView" using following script.


USE[Codefari]
GO
IFEXISTS(SELECT 1 FROMsys.sql_modulesWHEREobject_id=  OBJECT_ID('dbo.EmployeeView')ANDOBJECTPROPERTY(object_id,'IsView')= 1)
BEGIN
    PRINT'View is exist'
END
ELSE
BEGIN
       PRINT'View is not exist'
END


Result
View is exist

Using OBJECT_ID() function
Using  OBJECT_ID() function we can check existing of view "EmployeeView" for same database. See following script.


USE[Codefari]
GO
IFOBJECT_ID(N'dbo.EmployeeView',N'V')ISNOTNULL
BEGIN
    PRINT'View is exist'
END
ELSE
BEGIN
       PRINT'View is not exist'
END


Result
View is exist


Viewing all articles
Browse latest Browse all 265

Trending Articles