Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Give DROP PROCEDURE a parameter

I'm using SqlServer for the first time, and in every single one of our create procedure scripts there is a block of code like below to remove the procedure if it already exists:

IF EXISTS (SELECT *
           FROM information_schema.routines
           WHERE routine_name = 'SomeProcedureName'
           AND routine_type = 'PROCEDURE'

BEGIN
    DROP PROCEDURE SomeProcedureName
END
//then the procedure definition

To stop cutting and pasting this boilerplate code in every file I would like to put this code in its own stored procedure so that instead the scripts would look like this:

DropIfRequired('SomeProcedureName')
//then the procedure definition

My attempt at a solution is:

CREATE PROCEDURE DropIfRequired
(
    @procedureName varchar
)
AS
IF EXISTS (SELECT * FROM information_schema.routines 
           WHERE routine_name = @procedureName 
           AND routine_type = 'PROCEDURE') 
BEGIN
    DROP PROCEDURE @procedureName
END

But I then get the following error:

Msg 102, Level 15, State 1, Procedure DeleteProcedure, Line 10 Incorrect syntax near '@procedureName'.

Any ideas how to do what I want?

like image 879
Argos Avatar asked Oct 10 '08 15:10

Argos


People also ask

How do you pass a parameter to a procedure?

To pass one or more arguments to a procedure In the calling statement, follow the procedure name with parentheses. Inside the parentheses, put an argument list. Include an argument for each required parameter the procedure defines, and separate the arguments with commas.

How do you drop a procedure?

The syntax to a drop a procedure in Oracle is: DROP PROCEDURE procedure_name; procedure_name. The name of the procedure that you wish to drop.

How do I drop a procedure in SQL?

Use SQL Server Management Studio Expand Databases, expand the database in which the procedure belongs, and then expand Programmability. Expand Stored Procedures, right-click the procedure to remove, and then select Delete.

What does drop procedure means?

DROP PROCEDURE — Removes the definition of a stored procedure.


1 Answers

The full answer is:

DECLARE @SQL VARCHAR(8000)
SELECT @SQL = 'USE ' + DB_NAME() + CHAR(10)
SET @SQL = @SQL + 'DROP PROCEDURE ' + @procName
--PRINT @SQL
EXEC(@SQL)

The one given by Andrew will only work if the default database for your login is set to the database you want. When using dynamic sql you get a new database context. So if you do not have a default database set you will execute the command from master.

like image 87
Cervo Avatar answered Sep 25 '22 21:09

Cervo