views:

37

answers:

2

Happy Monday o/

I'm looking to do the following within a stored proc

  select @parameter="fooproc"
  drop procedure @parameter

instead of

  drop procedure fooproc

But it's choking with a syntax error. Is there some way I can bend this to my will? I would've expected to be able to do this.

I've tried a few permutations of type declaration of @parameter to no avail.

Thoughts?

+2  A: 

Only with dynamic SQL:

DECLARE @sql AS VARCHAR(2000)

SELECT @sql = STR_REPLACE('drop procedure {@parameter}', '{@parameter}', @parameter)

EXEC ( @sql )

I like to validate object names against database metadata before doing things like this. This protects against errors up front and even injection in the later dynamic section.

i.e. something like:

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = @parameter)
BEGIN
    DECLARE @sql AS VARCHAR(2000)
    SELECT @sql = STR_REPLACE('drop procedure {@parameter}', '{@parameter}', @parameter)
    EXEC ( @sql )
END
Cade Roux
Almost ;) in sybase it's: STR_REPLACE.( In the interest of brevity, I left out the part where I did the validation, since that works ;-) Thanks o/
Michael Wilson
@Michael Wilson I thought for sure they'd be the same on both dialects of Transact-SQL ;-)
Cade Roux
A perfectly reasonable assumption ;)
Michael Wilson
A: 
EXECUTE IMMEDIATE 'drop procedure ' || @parameter;
Zerofiz