Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Table selection

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?

like image 781
Drakullmonkey Avatar asked Jul 17 '26 14:07

Drakullmonkey


2 Answers

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)
like image 56
RichardTheKiwi Avatar answered Jul 19 '26 12:07

RichardTheKiwi


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.

like image 38
Ocaso Protal Avatar answered Jul 19 '26 10:07

Ocaso Protal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!