Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping tables using dynamic SQL

I am having trouble with my SQL stored procedure, specifically passing in VARCHAR() as a table name using it.

My code (not working) is:

CREATE PROCEDURE DeleteUser 

 @Username VARCHAR(50)

    AS
    BEGIN

    --DROP THE SURF TABLE
    IF EXISTS (SELECT 1 
      FROM sysobjects 
      WHERE xtype='u' AND name=@Username + '_table') 
          DROP TABLE @Username + '_table'  

 END
GO

However, on execution it errors at the DROP TABLE @Username + '_table' line.

What could I be doing incorrectly?

I am using MS SQL Server 2008 if it matters, called from C#.

like image 705
Brett Avatar asked Dec 27 '22 20:12

Brett


1 Answers

The DROP TABLE statement can't be parametrised as you are trying. You would need dynamic SQL.

DECLARE @DynSql nvarchar(max) = 'DROP TABLE ' + QUOTENAME(@Username + '_table');
EXEC(@DynSql);
like image 62
Martin Smith Avatar answered Jan 15 '23 10:01

Martin Smith