0

I am very new to SQL. I want to access a variable dynamically in a select statement.

declare @sql NVARCHAR(MAX)
declare @tableName varchar(100)
set @tableName='xxxx'

set @sql='select * from ' +@tableName+ 
EXEC sys.sp_executesql @sql

But every time I am executing the above query I am getting an error:

Incorrect syntax near the keyword 'EXEC'.
2
  • 3
    remove the + after @tableName. Should be +@tableName Commented Mar 3, 2014 at 18:41
  • Thanks Rick.It's a silly mistake ..anyways appreciate your help.. Commented Mar 3, 2014 at 18:44

3 Answers 3

1
declare @sql NVARCHAR(MAX);
declare @tableName NVARCHAR(128);
set @tableName='xxxx';

SET @sql = N'select * from ' + QUOTENAME(@tableName)
EXECUTE sp_executesql @sql

Use QUOTENAME() Function when concertinaing passed variables from users to your dynamic sql. It protects you against possible sql injection attack.

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

1 Comment

Very slick method of protecting against injection. Thanks.
0

You've got an extra plus sign after @tableName - remove it:

set @sql='select * from ' +@tableName  /*+ */
EXEC sys.sp_executesql @sql

Comments

0

You had one too many plus(+) signs around @table name. Please note that this method is wide open to an injection attack though.

declare @sql NVARCHAR(MAX)
declare @tableName varchar(100)
set @tableName='xxxx'

set @sql='select * from ' +@tableName
EXEC sys.sp_executesql @sql

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.