How do I use SQL Server table name in select query with a variable?

36,074

you have to use dynamic sql execution

wrap your statement in @selectstr

use exec sp_executesql @selectstr

Share:
36,074
Pinu
Author by

Pinu

I am web developer and enjoy writing code!

Updated on May 10, 2020

Comments

  • Pinu
    Pinu about 4 years

    Is this incorrect, can't we pass the table name to a select query dynamically?

    This is giving me a error 'Must declare the table variable @TblName'

    DECLARE @TblName VARCHAR(30)
    SET @TblName = 'User'
    SELECT * 
    FROM @TblName