Showing posts with label duties. Show all posts
Showing posts with label duties. Show all posts

Monday, February 20, 2012

Passing table name as parameter in stored procedure

Hey guys,
Im trying to create a store procedure that will perform certain duties on a
given table. The table name will be passed as a parameter.
The problem is I am not allowed to use the parameter as a tablename, so the
following queries are rejected:
SELECT #temp.[id] as SForceID, @.Table.[id] as OppID INTO #Temp2 FROM @.Table
LEFT OUTER JOIN #Temp ON #Temp.[id] = @.Table.[id]
DELETE FROM @.Table WHERE [id] IN (SELECT OppID FROM #Temp2 WHERE SForceID IS
NULL)
How do I achieve this? Is it doable? Is it perhaps a limitation?
Thank you in advance.Juan,
It is doable using dynamic sql but you may need to think about the
design.These are well discussed in the below article by Erland Sommarskog:
The Curse and Blessings of Dynamic SQL
http://www.algonet.se/~sommar/dynamic_sql.html#Dyn_table
Dinesh.
SQL Server FAQ at
http://www.tkdinesh.com
"Juan Romero" <juanja01@.optonline.net> wrote in message
news:%23M9Mi2iUDHA.1916@.TK2MSFTNGP12.phx.gbl...
> Hey guys,
> Im trying to create a store procedure that will perform certain duties on
a
> given table. The table name will be passed as a parameter.
> The problem is I am not allowed to use the parameter as a tablename, so
the
> following queries are rejected:
> SELECT #temp.[id] as SForceID, @.Table.[id] as OppID INTO #Temp2 FROM
@.Table
> LEFT OUTER JOIN #Temp ON #Temp.[id] = @.Table.[id]
> DELETE FROM @.Table WHERE [id] IN (SELECT OppID FROM #Temp2 WHERE SForceID
IS
> NULL)
> How do I achieve this? Is it doable? Is it perhaps a limitation?
> Thank you in advance.
>