1

I have a dynamic SQL query

DECLARE @ItemAreaCode NVARCHAR(MAX) = 'A062',
        @SQLStringDropTable NVARCHAR(MAX);

SET @SQLStringDropTable= 'DROP TABLE' + ' ' +
                         '[@ItemAreaCode].[ChangedRMAllocation]'

PRINT @ItemAreaCode

EXEC sp_executesql @SQLStringDropTable , N'@ItemAreaCode NVARCHAR(MAX)', @ItemAreaCode;

But when I execute this, I get this error:

Msg 3701, Level 11, State 5, Line 1
Cannot drop the table '@ItemAreaCode.ChangedRMAllocation', because it does not exist or you do not have permission.

And the printed query is..

DROP TABLE [@ItemAreaCode].[ChangedRMAllocation];

What I need is:

DROP TABLE [A062].[ChangedRMAllocation];

3 Answers 3

3

You are setting you parameter as a string within the dynamic SQL. @ItemAreaCode should not be included.

This should work :

DECLARE @ItemAreaCode NVARCHAR(MAX) = 'A062',
@SQLStringDropTable NVARCHAR(MAX);

    SET @SQLStringDropTable= 'DROP TABLE' + ' [' 
                            + @ItemAreaCode +  '].[ChangedRMAllocation]'

    PRINT @ItemAreaCode
    EXEC (@SQLStringDropTable);

Hope this helps

Sign up to request clarification or add additional context in comments.

3 Comments

Agree that the variable should be expanded in the string (although better with quotename), but why do you still pass it as a parameter to sp_executesql ?
@Andomar I need to write a query preventing sql injection here. That's why I used sp_executesql and pass parameters in to it. If this answer is not the right way how to do that
@tarzanbappa: This answer is vulnerable to SQL injection through @ItemAreaCode = ']; drop database importantstuff; --' for example. You can't pass table names as parameters. Use quotename to avoid SQL injection.
1

You probably meant to expand the variable:

DECLARE @ItemAreaCode sysname = 'A062',
    @SQLStringDropTable NVARCHAR(MAX);

SET @SQLStringDropTable = 
    'DROP TABLE ' + quotename(@ItemAreaCode) + '.[ChangedRMAllocation]';
EXEC (@SQLStringDropTable);

2 Comments

If the parameter is not a table name, Can I use a query like mine in the question?
It's better to avoid dynamic SQL if you can. Parameterized queries are almost always preferred.
1

Try this

DECLARE @ItemAreaCode NVARCHAR(MAX) = 'A062'
    ,@SQLStringDropTable NVARCHAR(MAX);

SET @SQLStringDropTable = 'DROP TABLE [' + @ItemAreaCode + '].[ChangedRMAllocation]'

EXEC (@SQLStringDropTable)

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.