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 derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getting the table name from another table...

Status
Not open for further replies.

e106199

Programmer
Joined
Nov 17, 2005
Messages
27
Location
US
hi all,
i have a table that keeps some table names. Depending on the given ID i go to this table get the table name and want to run a select statement over this table. Here is what i did so far(this is running in a stored procedure):
.......
DECLARE @TABLENAME VARCHAR(50)
set @TABLENAME = (SELECT TABLENAME FROM typeTable WHERE TYPEID = @p1) --now the @tablename is the name of the table i want

select myCODE from anotherTable
where ID = (SELECT ID2 FROM @TABLENAME WHERE ID = @p1)
.........
here i m getting a "Must declare variable @TABLENAME". Its declared i think so i dont know what am i doing wrong here.
Any ideas?
thanks in advance
-shane
 
Something like this (untested of course, but it should work)

DECLARE @TABLENAME VARCHAR(50)
set @TABLENAME = (SELECT TABLENAME FROM typeTable WHERE TYPEID = @p1) --now the @tablename is the name of the table i want


declare @SQL varchar(500)
create table #temp (id int)

select @SQL ='insert into #temp SELECT ID2 FROM ' + @TABLENAME +' WHERE ID = ' + convert(varchar,@p1) + ')'
exec (@SQL) --print to see statement --print @SQL

select myCODE from anotherTable a join #temp t on a.ID = t.id

Denis The SQL Menace
SQL blog:
Personal Blog:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top