SQL table selection

I am trying to create some ways to dynamically select a table to start a procedure based on an identifier sent to the database. Sort of:

@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?

+3
source share
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)
+3
source

In MS SQL Server, you can use sp_executesql to perform dynamic queries. Read the Curse and blessings of dynamic SQL , it helped me a lot.

+2
source

Source: https://habr.com/ru/post/1791444/


All Articles