-1

Am new to T-SQL. I have a variable holding table name. How I query the same table using this variable as

DECLARE @tb_name varchar(300)
SET @tb_name = 'tbl_deleted_shipmentdata_record'
select * from  @tb_name
Robert_Junior
  • 1,122
  • 1
  • 18
  • 40
  • 1
    just search for dynamic sql, it's been asked many times, see the below duplicate – Tanner Jun 24 '15 at 10:28
  • I don't know th term for searching. Thanks a lot – Robert_Junior Jun 24 '15 at 10:34
  • @Robert_Junior, before you go down the dynamic SQL path, peruse SQL Server MVP Erland Sommarskog's thorough article on the topic. It's not just a question of how you to do this, but should you. http://www.sommarskog.se/dynamic_sql.html – Dan Guzman Jun 24 '15 at 10:42

2 Answers2

4

YOu need to write dynamic SQL for that.

DECLARE @tb_name varchar(300)
SET @tb_name = 'tbl_deleted_shipmentdata_record'

Declare @SQL Nvarchar(Max)
 SET @SQL = 'select * from '+ @tb_name
Exec SP_ExecuteSQL @SQL
Arun Gairola
  • 884
  • 4
  • 14
3

You have to use dynamic query:

DECLARE @tb_name VARCHAR(300)
SET @tb_name = 'tbl_deleted_shipmentdata_record'

DECLARE @sql NVARCHAR(300)  = 'select * from ' + QUOTENAME(@tb_name)
EXEC( @sql)

QUOTENAME function surrounds @tb_name variable with [tbl_deleted_shipmentdata_record]. Just to minimize risk of sql injection.

Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75