Tag Archives: OBJECT_ID()

How to check if a Function exists in Sql Server

Many a times we come across a scenario where we need to execute some code based on whether a User Defined Function exists or not. There are different ways of identifying the Function existence in Sql Server, in this article will list out the commonly used approaches. Let me know which approach you use and reason for the same.

To demonstrate these different approaches let us create a sample database with an Inline Table Valued function by executing the following script:

CREATE DATABASE SqlHintsFunctionExists
GO
USE SqlHintsFunctionExists
GO
--Create Inline Table Valued function
CREATE FUNCTION dbo.GetEmployeeDetail()
RETURNS TABLE
AS
RETURN (SELECT 1 AS Id, 'Basavaraj' AS Name)
GO

[ALSO READ] How to check if a Stored Procedure exists in Sql Server

Approach 1: Using sys.objects catalog view

We can write a query like below to check if a GetEmployeeDetail User Defined Function exists in the current database in any schema.

USE SqlHintsFunctionExists
GO
IF EXISTS (SELECT 1 FROM sys.objects 
           WHERE Name = 'GetEmployeeDetail' 
             AND Type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
BEGIN
    PRINT 'User defined function Exists'
END

RESULT:
Function Exists Usig Sys Objects Example 1

The above query checks the existence of the object whose name is GetEmployeeDetail across all the schemas in the current database which is one of the below function type:

Type Type Description
FN Scalar function
IF Inline table-valued function
TF Table-valued-function
FS Assembly (CLR) scalar-function
FT Assembly (CLR) table-valued function

In Sql Server object names are unique, so it is really not required to mention the type in the where clause of the sys.objects query. But it is always better practice to mention type, reason is sys.objects contains the rows for not just function it also has records for views, stored Procedures etc
If you want to check the existence of the User Defined Function in a specified Schema, then we can re-write the query like below:

USE SqlHintsFunctionExists
GO
IF EXISTS (SELECT 1 FROM sys.objects 
           WHERE Name = 'GetEmployeeDetail' 
	    AND schema_id = SCHEMA_ID('dbo') --Schema name 'dbo'
	    AND Type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
BEGIN
    PRINT 'User defined function Exists'
END

RESULT:
Function Exists Usig Sys Objects Example 2

If you want check the existence of a user defined function in a database other than the contextual database then we can re-write the above query as below where sys.objects is specified by three part name:

IF EXISTS (SELECT 1 FROM SqlHintsFunctionExists.sys.objects 
           WHERE Name = 'GetEmployeeDetail' 
            AND schema_id = SCHEMA_ID('dbo') --Schema name 'dbo'
            AND Type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
BEGIN
    PRINT 'User defined function Exists'
END

RESULT:
Function Exists Usig Sys Objects Example 3

[ALSO READ] How to check if a Database exists in Sql Server

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a GetEmployeeDetail function exists in the current database.

USE SqlHintsFunctionExists
GO
IF OBJECT_ID(N'dbo.GetEmployeeDetail') IS NOT NULL
BEGIN
    PRINT 'User defined function Exists'
END

RESULT:
Function Exists Usig OBJECT ID Example 1

Specifying the Database Name and Schema Name parts for the Function Name is optional. But specifying Database Name and Schema Name provides an option to check the existence of the user defined function in the specified database and within a specified schema, instead of checking in the current database across all the schemas. The below query shows that, even though the current database is MASTER database, we can check the existence of the GetEmployeeDetail function in the dbo schema in the SqlHintsFunctionExists database.

USE MASTER
GO
IF OBJECT_ID(N'SqlHintsFunctionExists.dbo.GetEmployeeDetail')
           IS NOT NULL
BEGIN
    PRINT 'User defined function Exists'
END

RESULT:
Function Exists Usig OBJECT ID Example 2

OBJECT_ID() function also accept the type of the object as a parameter. We can specify one of the type of the function listed in the approach 1. In the below example we are checking whether GetEmployeeDetail Table-Valued function (i.e type IF) existing in the SqlHintsFunctionExists database within the dbo schema.

USE MASTER
GO
IF OBJECT_ID(N'SqlHintsFunctionExists.dbo.GetEmployeeDetail'
             , N'IF') IS NOT NULL
BEGIN
    PRINT 'User defined function Exists'
END

RESULT:
Function Exists Usig OBJECT ID Example 3

Let us modify the above statement and specify the type as ‘FN’ (i.e. Scalar function):

USE MASTER
GO
IF OBJECT_ID(N'SqlHintsFunctionExists.dbo.GetEmployeeDetail'
             , N'FN') IS NOT NULL
	BEGIN
		PRINT 'User defined function Exists'
	END
ELSE
	BEGIN
		PRINT 'User defined function doesn''t Exists'
	END

RESULT:
Function Exists Usig OBJECT ID Example 4

From the result we can see that the function GetEmployeeDetail doesn’t exists in the SqlHintsFunctionExists database. This is because we have specified the type of the object as FN (i.e. scalar function) in OBJECT_ID function instead of IF (i.e. Table-Valued function).

[ALSO READ] How to check if a Table exists in Sql Server

Approach 3: Using INFORMATION_SCHEMA.ROUTINES View

We can use the INFORMATION_SCHEMA.ROUTINES view to check the existence of the function as shown below:

USE SqlHintsFunctionExists
GO
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.ROUTINES 
           WHERE ROUTINE_NAME = 'GetEmployeeDetail' 
            AND ROUTINE_TYPE = 'FUNCTION') 
	BEGIN
		PRINT 'User defined function Exists'
	END
GO

RESULT:
Function Exists Using Information Schema Routine Example

This view does has the ROUTINE_SCHEMA column, but as suggested in MSDN we should avoid using it for identifying the schema of the object.

[ALSO READ] How to check if Temp table exists in Sql Server?

Approach 4: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog view sys.objects instead of sys.sysobjects system table directly to check the existence of the function.

USE SqlHintsFunctionExists
GO
IF EXISTS(SELECT * FROM sys.sysobjects  
     WHERE name = 'GetEmployeeDetail' 
      AND Type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
BEGIN
	PRINT 'User defined function Exists'
END

RESULT:
Function Exists Using sys sysobjets Example

How to check if a VIEW exists in Sql Server

Many a times we come across a scenario where we need to execute some code based on whether a View exists or not. There are different ways of identifying the View existence in Sql Server, this article will list out the commonly used approaches. Let me know which approach you use and reason for the same.

[ALSO READ] Views in Sql Server

To demonstrate these different approaches let us create a sample database SqlHintsDemoDB. Create Customers Table with sample data and a vwGetCustomerInfo View by the following script:

CREATE DATABASE SqlHintsDemoDB
GO
USE SqlHintsDemoDB
GO
--Create Customer table
CREATE TABLE dbo.Customers
( CustomerID int Identity(1,1), FirstName NVarchar(50),
  LastName NVarChar(50), Phone varchar(50))
GO
--Insert sample records into the customer table
INSERT INTO Customers (FirstName, LastName, Phone)
Values ('Kalpana','Biradar','2727272727'),
       ('Basavaraj','Biradar','1616161616')
GO
--Create view
CREATE VIEW dbo.vwGetCustomerInfo
AS
 SELECT CustomerID, FirstName +' ' + LastName FullName
 FROM CUSTOMERS
GO
SELECT * FROM dbo.vwGetCustomerInfo
GO

[ALSO READ] How to check if a Table exists in Sql Server

Approach 1: Using sys.views catalog view

We can write a query like below to check if a view vwGetCustomerInfo exists in the current database in any schema.

IF EXISTS(SELECT 1 FROM sys.views 
     WHERE Name = 'vwGetCustomerInfo')
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-sys.views 1

The above query checks the existence of the vwGetCustomerInfo View across all the schemas in the current database. Instead of this if you want to check the existence of the View in a specified Schema then we can re-write the above query as below:

IF EXISTS(SELECT 1 FROM sys.views 
   WHERE object_id = OBJECT_ID('dbo.vwGetCustomerInfo'))
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-sys.views 2

If you want to check the existence of a View in a database other than the current contextual database, then we can re-write the above query as shown below:

IF EXISTS(SELECT 1 FROM SqlHintsDemoDB.sys.views 
   WHERE object_id = OBJECT_ID('dbo.vwGetCustomerInfo'))
	BEGIN
		PRINT 'View Exists'
	END
GO

RESULT:
Check-View-Existence-using-sys.views 3
[ALSO READ] How to check if a record exists in table

Approach 2: Using sys.objects catalog view

sys.views catalog view inherits the rows from the sys.objects catalog view, sys.objects catalog view is referred to as the base view whereas sys.views is referred to as derived view. sys.views will return the rows only for the views, whereas sys.objects view apart from returning the rows for Views, it returns rows for the objects like: tables, stored procedure etc.

We can write a script like below to check the existence of a view in the current contextual database:

IF EXISTS (SELECT * FROM sys.objects
            WHERE object_id = OBJECT_ID('dbo.vwGetCustomerInfo')
                    AND type = 'V') 
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-sys.objects

Approach 3: Using sys.sql_modules Catalog View

We can use the sys.sql_modules catalog view to check the existence of the View as shown below:

USE SqlHintsDemoDB
GO
IF EXISTS (SELECT 1 FROM sys.sql_modules
   WHERE object_id =  OBJECT_ID('dbo.vwGetCustomerInfo')
   AND OBJECTPROPERTY(object_id, 'IsView') = 1) 
	BEGIN
		PRINT 'View Exists'
	END

RESULT
Check-View-Existence-using-sys.sql_modules

Approach 4: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if the View vwGetCustomerInfo exists in the current database.

IF OBJECT_ID(N'dbo.vwGetCustomerInfo', N'V') IS NOT NULL
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-Object_Id function

Specifying the Database Name and Schema Name parts for the View Name is optional. But specifying Database Name and Schema Name provides an option to check the existence of the View in the specified database and within a specified schema, instead of checking in the current database across all the schemas. The below query shows that, even though the current database is MASTER database, we can check the existence of the view vwGetCustomerInfo in the dbo schema in the SqlHintsDemoDB database.

USE master	
GO
IF OBJECT_ID(N'SqlHintsDemoDB.dbo.vwGetCustomerInfo', 
                  N'V') IS NOT NULL
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-Object_Id function 2

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.views/sys.sql_modules instead of sys.sysobjects system table directly to check the existence of the View.

USE SqlHintsDemoDB
GO
IF EXISTS(SELECT 1 FROM sys.sysobjects  
     WHERE id = OBJECT_ID(N'dbo.vwGetCustomerInfo') 
                      AND xtype=N'V')
	BEGIN
		PRINT 'View Exists'
	END

RESULT:
Check-View-Existence-using-sys.sysobjects

[ALSO READ] :
How to check if a Database exists
How to check if a Table exists
How to check if a Stored Procedure exists in Sql Server
How to check if Temp table exists
How to check if a record exists in table

How to check if a Stored Procedure exists in Sql Server

Many a times we come across a scenario where we need to execute some code based on whether a Stored Procedure exists or not. There are different ways of identifying the Stored Procedure existence in Sql Server, in this article will list out the commonly used approaches. Let me know which approach you use and reason for the same.

To demonstrate these different approaches let us create a sample database with a Table and a Stored Procedure by the below script:

CREATE DATABASE SqlHintsDemoDB
GO
USE SqlHintsDemoDB
GO
CREATE TABLE dbo.Customers (CustId INT, Name NVARCHAR(50))
GO
CREATE PROCEDURE dbo.GetCustomers(@CustId AS INT)
AS
BEGIN
	SELECT * FROM  dbo.Customers WHERE CustId = @CustId
END
GO

[ALSO READ] How to check if a Table exists in Sql Server

Approach 1: Using sys.procedures catalog view

We can write a query like below to check if a GetCustomers Stored Procedure exists in the current database in any schema.

USE SqlHintsDemoDB
GO
IF EXISTS(SELECT 1 FROM sys.procedures 
          WHERE Name = 'GetCustomers')
BEGIN
	PRINT 'Stored Procedure Exists'
END

RESULT:
Check Stored Procedure Existence using sys.procedures

The above query checks the existence of the GetCustomers Stored Procedure across all the schemas in the current database. Instead of this if you want to check the existence of the Stored Procedure in a specified Schema then we can re-write the above query as below:

USE SqlHintsDemoDB
GO
IF EXISTS(SELECT 1 FROM sys.procedures 
          WHERE object_id = OBJECT_ID(N'dbo.GetCustomers'))
BEGIN
	PRINT 'Stored Procedure Exists'
END

RESULT:
Check Stored Procedure Existence using sys.procedures2

If you want to check the existence of a stored procedure in a database other than the current contextual database, then we can use the script like below:

USE MASTER
GO
IF EXISTS(SELECT 1 FROM SqlHintsDemoDB.sys.procedures
 WHERE object_id=OBJECT_ID(N'SqlHintsDemoDB.dbo.GetCustomers'))
BEGIN
	PRINT 'Stored Procedure Exists'
END

RESULT:
Check Stored Procedure Existence using sys.procedures3

Note: sys.procedures catalog view contains a row for each object of the below type:

Type Description
P SQL Stored Procedure
PC Assembly (CLR) stored-procedure
RF Replication-filter-procedure
X Extended stored procedure

If you are looking for only Sql Stored Procedure, then in sys.procedures catalog views query you can add the filter AND condition as: Type = N’P’.

[ALSO READ] How to check if a record exists in table

Approach 2: Using sys.objects catalog view

sys.procedures catalog view inherits the rows from the sys.objects catalog view, sys.objects catalog view is referred to as base view where as sys.procedures is referred to as derived view. sys.procedures will return the rows only for the stored procedures whereas sys.objects view apart from returning the rows for stored procedures, it returns rows for the objects like: tables, views etc.

We can write a script like below to check the existence of a stored procedure in the current contextual database:

IF EXISTS (SELECT * FROM sys.objects
            WHERE object_id = OBJECT_ID(N'dbo.GetCustomers')
                    AND type IN ( N'P', N'PC',N'X',N'RF')) 
BEGIN
	PRINT 'Stored Procedure Exists'
END

RESULT:
Check Stored Procedure Existence using sys.objects

If you want check the existence of a stored procedure in a database other than the contextual database then we can re-write the above query by using three part naming convention as shown below:

USE master
GO
IF EXISTS (SELECT * FROM SqlHintsDemoDB.sys.objects
 WHERE object_id=OBJECT_ID(N'SqlHintsDemoDB.dbo.GetCustomers')
      AND type IN ( N'P', N'PC',N'X',N'RF')) 
BEGIN
	PRINT 'Stored Procedure Exists'
END

RESULT:
Check Stored Procedure Existence using sys.objects2

[ALSO READ] How to check if a Temp table exists

Approach 3: Using sys.sql_modules Catalog View

We can use the sys.sql_modules catalog view to check the existence of the Stored Procedure as shown below:

USE SqlHintsDemoDB
GO
IF EXISTS (SELECT 1 FROM sys.sql_modules
   WHERE object_id =  OBJECT_ID(N'dbo.GetCustomers') 
   AND OBJECTPROPERTY(object_id, N'IsProcedure') = 1) 
BEGIN
	PRINT 'Stored Procedure Exists'
END

RESULT
Check Stored Procedure Existence using sys.sql_modules

[ALSO READ] How to check if a Database exists

Approach 4: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a GetCustomers Stored procedure exists in the current database.

USE SqlHintsDemoDB
GO
IF OBJECT_ID(N'dbo.GetCustomers', N'P') IS NOT NULL
BEGIN
	PRINT 'Stored Procedure Exists'
END

RESULT:
Check Stored Procedure Existence using OBJECT_ID function

Specifying the Database Name and Schema Name parts for the Stored Procedure Name is optional. But specifying Database Name and Schema Name provides an option to check the existence of the stored procedure in the specified database and within a specified schema, instead of checking in the current database across all the schemas. The below query shows that, even though the current database is MASTER database, we can check the existence of the GetCustomers stored procedure in the dbo schema in the SqlHintsDemoDB database.

USE MASTER
GO
IF OBJECT_ID(N'SqlHintsDemoDB.dbo.GetCustomers', N'P')
     IS NOT NULL
BEGIN
	PRINT 'Stored Procedure Exists'
END

RESULT:
Check Stored Procedure Existence using OBJECT_ID function2

[ALSO READ] How to check if a View exists

Approach 5: Using INFORMATION_SCHEMA.ROUTINES View

We can use the INFORMATION_SCHEMA.ROUTINES view to check the existence of the stored procedure as shown below:

USE SqlHintsDemoDB
GO
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.ROUTINES 
  WHERE ROUTINE_NAME = 'GetCustomers' 
        AND ROUTINE_TYPE = 'PROCEDURE') 
BEGIN
    PRINT 'Stored Procedure Exists'
END

RESULT
Check Stored Procedure Existence using INFORMATION_SCHEMA.ROUTINES

Approach 6: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.procedures/sys.sql_modules instead of sys.sysobjects system table directly to check the existence of the stored procedure.

USE SqlHintsDemoDB
GO
IF EXISTS(SELECT 1 FROM sys.sysobjects  
     WHERE id = OBJECT_ID(N'dbo.GetCustomers') AND xtype=N'P' )
BEGIN
    PRINT 'Stored Procedure Exists'
END

RESULT:
Check Stored Procedure Existence using sys.sysobjects

[ALSO READ] :
How to check if a Database exists
How to check if a Table exists
How to check if a View exists
How to check if Temp table exists
How to check if a record exists in table