I want to pass table name as parameter | SQL Server Performance Forums

SQL Server Performance Forum – Threads Archive

I want to pass table name as parameter

Hi,
Please check following statments Declare @value varchar(100)
Select * from table where Column = @value
But i have to do like Declare @Table varchar(100)
Select * from @Table
Only way is Dynamic SQL Declare @Table varchar(100)
set @Table =’YourTable’
EXEC(‘Select * from ‘[email protected]) Madhivanan Failing to plan is Planning to fail
Use sp_executesql
From BOL
sp_executesql
Executes a Transact-SQL statement or batch that can be reused many times, or that has been built dynamically. The Transact-SQL statement or batch can contain embedded parameters. —————————————-
http://spaces.msn.com/members/dineshasanka

DECLARE @SQL NVARCHAR(1000), @Table NVARCHAR(130) SET @Table = ‘your_table’
SET @SQL = ‘SELECT * FROM ‘ + @Table –debugging
PRINT @SQL EXEC sp_executesql @SQL Note: you can have issues with permissions. Including this code into store procedure you will must grant user all needed permissions to underlying objects (in this case SELECT permissions on ‘your_table’). Using following code in stored procedure: SELECT * FROM your_table you have only grant execute permissions to user.
The most problems are incase you have to grant insert update or delete, givint to user ability to change data bypassing db interface … Maksim
Check this:http://www.sommarskog.se/dynamic_sql.html and see if that is really what you want to do. —
Frank Kalis
Microsoft SQL Server MVP
http://www.insidesql.de
Heute schon gebloggt?http://www.insidesql.de/blogs
Ich unterstuetze PASS Deutschland e.V. http://www.sqlpass.de)
]]>