问题
I have a #temp
table where I have names of stored procedures.
DECLARE @object VARCHAR(200)
SET @object = (SELECT Top 1 Te.[this Object...] From #Temp Te)
IF OBJECT_ID(@object) IS NOT NULL
DROP PROCEDURE @object
But on last step I get error
Incorrect syntax near '@object'.
Is this because @object
is of type VARCHAR
or what ?
This is for SQL Server 2012
回答1:
you can't do it like that. You need to use dynamic sql. Something like :
DECLARE @object NVARCHAR(200)
DECLARE @sql NVARCHAR(max)
SET @object = (SELECT Top 1 Te.[this Object...] From #Temp Te)
IF OBJECT_ID(@object) IS NOT NULL
BEGIN
SET @sql = 'DROP PROCEDURE ' + @object
sp_executesql @sql
END
回答2:
Have a look here:
https://dba.stackexchange.com/questions/47186/how-can-i-drop-a-stored-procedure-whose-name-is-in-a-variable
You need to write an sql statement and execute it seperately.
Part from that answer:
declare @sql varchar(64);
set @sql = 'drop proc ' + @stored_procedure_name;
exec(@sql);
And you can replace @stored_procedure_name with @object
回答3:
DROP PROCEDURE needs an object not an varchar
try:
EXECUTE ('DROP PROCEDURE ' + @object)
来源:https://stackoverflow.com/questions/38744149/drop-procedure-throws-syntax-error