Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using a variable for a table_name in select

Status
Not open for further replies.

skertz

Programmer
Jan 19, 2001
3
US
It is possible to declare a variable, set it and then use it in a select statement like e.g:

declare @my_var varchar(31), @db varchar(31)
set @db = 'TEST'
set @my_var = @db + '..sysobjects'

select * from @my_var


I'm looking to query other database tables from inside a procedure.
 
YES, but you will have to use exec to execute the query

eg.

declare @my_var varchar(31)
declare @db varchar(31)

set @db = 'TEST'
set @my_var = @db + '..sysobjects'

exec 'select * from ' + @my_var


hope this helps,

Chris Dukes
 
Thanks Chris!! You got me going down the right path.

The EXEC works, but you must enclose it in () like the following.

exec ('select * from' + @my_var)

THANKS AGAIN!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top