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)
 Using variable in from clause

Author  Topic 

KunalDes
Starting Member

4 Posts

Posted - 2009-06-04 : 01:37:51
Hello friends,

I want to use a variable which contains a table name. And then I want to use this variable in the from clause of a select query. Code will be something as below:

--Variable declaration
DECLARE @tablename VARCHAR(100);
SET @tablename = 'CustomerTable';

--Use Variable in from clause
SELECT * FROM @tablename;

Can anyone please tell me how to accomplish this kind of functionaliry.....

Thanks and regards,
Kunal

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2009-06-04 : 01:40:52
Nope. This is not possible. You have to use Dynamic SQL

read this before you decide to go into it.
The Curse and Blessings of Dynamic SQL


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

senthil_nagore
Master Smack Fu Yak Hacker

1007 Posts

Posted - 2009-06-04 : 02:05:03
just use Dynamic sql

@query='SELECT * FROM '+ @tablename

exec(@query)

Thats all so simple.....


Senthil.C
------------------------------------------------------
[Microsoft][ODBC SQL Server Driver]Operation canceled
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-06-04 : 13:08:19
quote:
Originally posted by senthil_nagore

just use Dynamic sql

@query='SELECT * FROM '+ @tablename

exec(@query)

Thats all so simple.....


Senthil.C
------------------------------------------------------
[Microsoft][ODBC SQL Server Driver]Operation canceled


be careful against sql injection attacks
Go to Top of Page
   

- Advertisement -