Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Selecting from a table

Author  Topic 

chillipeppers
Starting Member

1 Post

Posted - 2002-01-07 : 11:35:25
I have archived tables e.g arch_2001_cust , arch_2000_cust
I have a report where you can select the year e.g. 200o,2001
I then have a stored procedure where I am passing the year e.g. sp_getinfo '2001' I build up my tablename from the year passed e.g
set @tabname = '[@arch_' + @SelYear + '_cust']
I then attempt to select from the correct table
e.g select * from [@tabname]. I get the following error
Server: Msg 208, Level 16, State 1, Procedure sp_getinfo, Line 8
Invalid object name '@tabName'. What am I doing wrong?

davidpardoe
Constraint Violating Yak Guru

324 Posts

Posted - 2002-01-07 : 11:43:50
You need to use dynamic SQL for this

declare @sql varchar(1000)

set @sql='select * from '+@tablename

exec (@sql)

Check the articles on dynamic SQL in the main part of the site for a better intro to this most useful area!

http://www.sqlteam.com/item.asp?ItemID=4599

============
The Dabbler!

Edited by - davidpardoe on 01/07/2002 11:44:38
Go to Top of Page

nr
SQLTeam MVY

12543 Posts

Posted - 2002-01-07 : 12:16:44
Have you thought about creating a partitioned view on the tables so that you do not need to use dynamic sql.

I normally don't advise views but this looks like a case where it could make things simpler.

It's also not a good idea to name procedures sp_

==========================================
Cursors are useful if you don't know sql.
Beer is not cold and it isn't fizzy.
Go to Top of Page
   

- Advertisement -