SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Using variable in from clause
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

KunalDes
Starting Member

4 Posts

Posted - 06/04/2009 :  01:37:51  Show Profile  Reply with Quote
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)

Singapore
17681 Posts

Posted - 06/04/2009 :  01:40:52  Show Profile  Reply with Quote
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
Time is always against us

Go to Top of Page

senthil_nagore
Flowing Fount of Yak Knowledge

India
1007 Posts

Posted - 06/04/2009 :  02:05:03  Show Profile  Visit senthil_nagore's Homepage  Send senthil_nagore a Yahoo! Message  Reply with Quote
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

India
52325 Posts

Posted - 06/04/2009 :  13:08:19  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000