Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored procedure to drop table

I have created a stored procedure that will drop a table if it exists in a database. When running the stored procedure with EXEC, I am getting the following error:

Msg 203, Level 16, State 2, Procedure sp_DropIfExists, Line 13 The name 'IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N'table_name') AND type = (N'U')) DROP TABLE [table_name]' is not a valid identifier.

However if i copy and paste the T-SQL that is generated into management studio, it seems to be running fine. Can someone explain why this is not valid? The fix would be nice, but I am really after the Why primarily, The How would be nice to though! Thanks in advance.

ALTER PROCEDURE [dbo].[sp_DropIfExists](@tableName VARCHAR(255)) 
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @SQL VARCHAR(MAX);
    SET @SQL = 'IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N''' + @tableName + ''') AND type = (N''U'')) DROP TABLE [' + @tableName + ']'
    PRINT @SQL;
    EXEC @SQL;
END
like image 647
SSISPissesMeOff Avatar asked May 18 '11 14:05

SSISPissesMeOff


1 Answers

you can use sp_execute

sp_executesql @SQL

for more information msdn document link

like image 62
maycil Avatar answered Oct 11 '22 17:10

maycil