SQL Server Function that receive table name as input variable to be used in CROSS APPLY

k5hmc34c  于 2023-05-05  发布在  其他
关注(0)|答案(1)|浏览(220)

I need to create a Db function that returns a list of GUID, but from different tables.
So I'm trying to create a db function, that get as input the name of the table, and return a list (table with only one field), but since I cannot use dynamic sql all I tried doesn't work.

How can I do that? Every db function I tried to create, doesn't even pass the "syntax" check, and now I'm stuck.

hrysbysz

hrysbysz1#

This is just a procedure and I specified the code field and all the values are returned without where The input must include the name of the table and the schema, separated by a comma I cannot use EXEC in functions, I had to use stored procedures

alter proc TestProc1-- '[dbo].[T1],[dbo].[T2]'      
       @ListTAble nvarchar(100)
as
    
drop table if exists #listvalues;drop table if exists #tables
create table #listvalues (datas uniqueidentifier)
select 
         '['+a.TABLE_SCHEMA+ '].' + '['+a.TABLE_NAME+ ']' as TAbleNAme
         ,ROW_NUMBER() over(order by TABLE_NAME) as rw  
into #tables         
from INFORMATION_SCHEMA.TABLES a
where '['+a.TABLE_SCHEMA+ '].' + '['+a.TABLE_NAME+ ']' in (select * from string_split(@ListTAble,',') )

declare @query varchar(max)=''
declare @Count int=(select count(*) from #tables)
declare @I int=1
while(@Count>=@I)
begin

   set @query=' insert into #listvalues (datas)  select Id from  ' + (select TAbleNAme from #tables where rw=@I)
   exec(@query)
   set @I=@I+1

end 
select  STRING_AGG(cast( datas as nvarchar(max)),',') from  #listvalues
create table T1(id uniqueidentifier,Name nvarchar(100))
create table T2(id uniqueidentifier,Name1 nvarchar(100))
create table T3(id uniqueidentifier,Name2 nvarchar(100))
insert into T1 (id,Name) values(NEWID(),'ff')
insert into T1 (id,Name) values(NEWID(),'ff')
insert into T1 (id,Name) values(NEWID(),'ff')
insert into T2 (id,Name1) values(NEWID(),'ff')
insert into T2 (id,Name1) values(NEWID(),'ff')
insert into T2 (id,Name1) values(NEWID(),'ff')
insert into T3 (id,Name2) values(NEWID(),'ff')
insert into T3 (id,Name2) values(NEWID(),'ff')
insert into T3 (id,Name2) values(NEWID(),'ff')
insert into T3 (id,Name2) values(NEWID(),'ff')

相关问题