Chetan
Chetan

Reputation: 129

Sqlserver temporary table name from variable

I am getting error when i run this query

declare @query varchar(700)
declare @tbl varchar(50)='#mytbl'
set @query='select check_details.id, check_details.point_no into '+ @tbl+ ' FROM check_details'
exec @query

What i am missing.

My error is Database 'select check_details' does not exist. Make sure that the name is entered correctly.

If i run

select check_details.id, check_details.point_no into #mytbl FROM check_details

This works perfectly

Upvotes: 1

Views: 2519

Answers (2)

Robert
Robert

Reputation: 25753

You have to add parentheses:

exec(@query)

Upvotes: 0

podiluska
podiluska

Reputation: 51494

Try

exec sp_executesql @query

or

exec (@query)

Upvotes: 1

Related Questions