I'm trying to create some means of dynamically selecting the table for a procedure to run on based on an ID sent to the database. Something like :
@TableId int
As
Declare @nameoftable varchar(50)
select @nameoftable = Nameoftable from tablelist where id = @tableid
-- returning on selected table
Select somestuff
from @nameoftable
Any ideas?
You need to use dynamic SQL
@TableId int
As
Declare @nameoftable varchar(50)
select @nameoftable = Nameoftable from tablelist where id = @tableid
-- returning on selected table
declare @sql nvarchar(1000)
set @sql = 'Select somestuff from ' + Quotename(@nameoftable)
exec(@sql)
In MS SQL Server you can use sp_executesql to execute dynamic queries. Read The Curse and Blessings of Dynamic SQL, it helped me alot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With