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 2005 Forums
 Transact-SQL (2005)
 Variable as table name

Author  Topic 

karuna
Aged Yak Warrior

582 Posts

Posted - 2007-06-28 : 17:12:04
can i pass a table name as variable?

DECLARE @tblname varchar(100)
SELECT @tblname = 'tbla'
SELECT Count(*) from @tblname -- I get error here..

I can wrap these select count(*) statement in a variable and use exec(@varname). But I'm wondering if the above is possible. This is in SQL SERVER 2005.

Thanks
Karunakaran

sshelper
Posting Yak Master

216 Posts

Posted - 2007-06-28 : 17:26:05
That's not possible. You have to use dynamic SQL for this.

SQL Server Helper
http://www.sql-server-helper.com
Go to Top of Page

karuna
Aged Yak Warrior

582 Posts

Posted - 2007-06-28 : 17:46:02
Thanks.

I thought this was supposed to be available in Sql Server 2005
Go to Top of Page

mobius
Starting Member

13 Posts

Posted - 2007-06-28 : 17:49:34
Think I'm having a similar problem over in my topic [url]http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=85728[/url]

Any reference on how to dynamically construct and execute a query like that?
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-06-30 : 08:59:30
quote:
Originally posted by karuna

can i pass a table name as variable?

DECLARE @tblname varchar(100)
SELECT @tblname = 'tbla'
SELECT Count(*) from @tblname -- I get error here..

I can wrap these select count(*) statement in a variable and use exec(@varname). But I'm wondering if the above is possible. This is in SQL SERVER 2005.

Thanks
Karunakaran


No. You cant
Make sure you read this fully
www.sommarskog.se/dynamic_sql.html

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -