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)
 Passing Table name as a parameter

Author  Topic 

gsvnreddy
Starting Member

3 Posts

Posted - 2007-05-24 : 01:20:18
Can anyone let me know how to pass table name as a parameter in select statement

E.g:
Declare @table_name varchar(50)

I pass this parameter to stored procedure which contain select statement like this

select * from @table_name

will it work?

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-05-24 : 01:23:25
It is not possible without resorting to Dynamic SQL.

Why do you want to do this ?
Take a look at this
http://www.sommarskog.se/dynamic_sql.html


KH

Go to Top of Page

gsvnreddy
Starting Member

3 Posts

Posted - 2007-05-24 : 01:57:45
Thanks KH

quote:
Originally posted by khtan

It is not possible without resorting to Dynamic SQL.

Why do you want to do this ?
Take a look at this
http://www.sommarskog.se/dynamic_sql.html


KH



Go to Top of Page

svicky9
Posting Yak Master

232 Posts

Posted - 2007-05-24 : 12:43:45
The Eg in ur case works like this

declare @sql varchar(1000)
declare @tablename varchar(100)

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

Vic

http://vicdba.blogspot.com
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-05-25 : 05:43:57
Make sure that you read that article

Madhivanan

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

Kristen
Test

22859 Posts

Posted - 2007-05-25 : 06:57:24
"The Eg in ur case works like this"

Indeedie ... but its still a horrid piece of code!

"Why do you want to do this ?"

@gsvnreddy: Explain why, someone here will probably have a good way around the problem you are facing. I very much double a generic "SELECT * FROM @table" is going to be a good answer!

Kristen

Go to Top of Page
   

- Advertisement -