4

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#.

1
  • Msg 102, Level 15, State 1, Procedure DeleteUser, Line 21 Incorrect syntax near '@Username'. Line 21 is the DROP TABLE line. Commented May 10, 2011 at 21:55

1 Answer 1

11

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.