How to drop a SQL Server stored procedure without error using the existence check?
To drop a SQL Server stored procedure and avoid errors, first test the existence of the procedure in the SQL Server database to condition the DROP PROCEDURE command. On the other hand, it is a good practice to always test the existence of SQL Server objects. In this case a stored procedure with the IF EXISTS command.
1. Script to Drop a stored procedure
Here is the basic T-SQL command to delete a SQL Server stored procedure:
DROP PROCEDURE dbo.uspGetClient; GO
2. DROP MS SQL procedures without error
First, how do you delete a SQL Server stored procedure without generating an error? That is, check if the object exists before deleting it with the SQL DROP command. To do this, use the T-SQL IF EXISTS function. As in this example, on SQL Server versions prior to 2016.
IF EXISTS ( SELECT name FROM sysobjects WHERE name = 'uspGetClient AND type = 'P ) DROP PROCEDURE dbo.uspGetClient; GO
Indeed, if the procedure does not exist the following error message is displayed, on English versions of SQL Server:
Cannot drop the procedure ‘uspGetClient’, because it does not exist or you do not have permission.
3. Existence tests integrated since SQL Server 2016
Note that since the SQL Server 2016 version, it is possible to test if a function, table or stored procedure exists and delete it with a single SQL command.
DROP PROCEDURE IF EXISTS dbo.uspGetClient; GO
4. Generate a dynamic script to delete all stored procedures
Finally, here is a request to generate an DDL script to delete all stored procedures from the database. The code uses the sys.procedures system view, stored in the msdb system database.
SELECT 'DROP PROCEDURE IF EXISTS ' + SCHEMA_NAME(schema_id) + '.' + [Name] + ';' AS [SQL_Query], SCHEMA_NAME(schema_id) AS [Schema_Name], [object_id], [type], [type_desc], [create_date] FROM sys.procedures order by 1;
The result is a column with one row for each stored procedure of user type. Each row contains a command to test the existence and delete the procedure. To use the code generated, two options are available.
- The first one is to copy and paste the DROP PROCEDURE code generated and execute it in another SSMS Window.
- The second is to add more code to automate the execution inside a T-SQL loop.
T-SQL tutorials on stored procedures
To go further, still about MS SQL stored procedures management using scripts, find more tutorials :
Be the first to comment