Sql-server – How to drop a stored procedure whose name is in a variable

sql serversql-server-2008-r2stored-procedurest-sql

Given a variable that contains a stored procedure name:

DECLARE @stored_procedure_name sysname;
SET @stored_procedure_name = 'some_stored_procedure_name';

How can I drop the stored procedure?

Best Answer

To do this, you must use dynamic SQL, as the statement DROP PROCEDURE cannot be parameterized.

As a bit of an aside, it's a good practice to always schema-qualify object names. You didn't specify the schema name in the question (or say that the variable contains a complete dot-separated name), so I've gone ahead and extended what you asked for to include it.

DECLARE @stored_procedure_schema sysname = NULL;
DECLARE @stored_procedure_name sysname = N'some_stored_procedure_name';

DECLARE @sql nvarchar(MAX) =
    N'DROP PROCEDURE ' +
        ISNULL(QUOTENAME(@stored_procedure_schema) + N'.', N'') +
        QUOTENAME(@stored_procedure_name) + N';';

EXEC(@sql);

This doesn't do any checking to see if the procedure actually exists or not before it attempts to drop it, so you'll get an error if it doesn't exist. It's trivial to use sys.procedures to check for existence, so I didn't bother with that, and you didn't ask for it either.

To preemptively answer your comment on the other answers, QUOTENAME will correctly escape any object name such that it ends up surrounded by square brackets. Specifically, yes, this does handle single quotes (and square brackets) within the procedure name itself.