I
I
Ilya2020-09-28 17:16:23
SQL
Ilya, 2020-09-28 17:16:23

How to put exec in a table function?

There are tables in the database with numbering (for example, clients_1, clients_2), the number changes every month. I want to make a table function that would return certain clients, giving the input just the number 1/2 ...
Inside the function, using dynamic sql, a query is formed with the name of the desired table, for example:

declare @tableNumber varchar(100)  --  на входе подаем 1/2/3...
declare @sql varchar(100)

set @sql = '
select *
into #tempTable
from dbo.clients_' + @tableNumber

exec(@sql)

return #tempTable


But you can't use exec inside a table function. As an alternative, I thought that I could put it all in a procedure, but then I would not be able to return the result as a table, i.e. I can't put it in a request.
And when creating a table using a procedure, you must remember to delete it later.
Any ideas how this can be solved in a less clumsy way?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question