Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 446
  • Last Modified:

SQL Variable - Table Name

Hi,

Is it possable to make a @variable in SQL that stores a Table name?

Is so, how would you do it?

Thank you.

0
Endelm
Asked:
Endelm
  • 2
  • 2
1 Solution
 
HuyBDCommented:
declare @tablename varchar(100)
set @tablename='tablename'

HuyBD;
0
 
HuyBDCommented:
you can even store query in variable then use exec to run it

declare @sqlvarchar(100)
set @sql='select * from tablename'
exec(@sql)
0
 
OtanaCommented:
What HuyBD is correct, but you can not select directly from the variable, like this:

SELECT * FROM @tablename

You'd have to use dynamic SQL, like this:

declare @SQL varchar(1000)
set @SQL = 'SELECT * FROM ' + @tablename
exec(@SQL)
0
 
EndelmAuthor Commented:
This doesn't work:

declare @TableName varchar(20)
set @TableName = 'dbo.SomeTable'

create table dbo.SomeTable
(id int,
name varchar(20)
)

insert into dbo.SomeTable(id,name)
values(0, 'John')

select * from @TableName
0
 
EndelmAuthor Commented:
Thank you.
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now