微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SQL:递归地应用和联合表函数

如何解决SQL:递归地应用和联合表函数

我使用的是 sql Server Management Studio 18。

我有一个函数,它将表名作为参数,并输出一个表,其中包含有关其他具有相同列的表的信息。每个表都有不同数量的列(是否也在其他表中)。输出是列名、表名和主题。这有效。 我想对我应用该函数的第一个表的结果集中的所有表应用相同的函数,并将其相互联合。

我知道我做错了什么 (dbo.TableStructure(firstTable.TableName)) 不起作用,因为该函数只针对 1 个参数而不是多个参数。但我不知道要改变什么才能使它正确。 函数代码

create function [dbo].[TableStructure](@table nvarchar(50))
returns table as return 
(
select c.name as 'ColumnName',t.name as 'TableName',s.Subject as 'Subject'
from sys.columns c join sys.tables t on c.object_id = t.object_id join dbo.tableSubjects s on t.name=s.name
where t.name <> @table and c.name in (select name from sys.columns where object_id = (select object_id from sys.tables where name = @table)))

应用函数代码

declare @table varchar(50) = 'Example';

with firstTable as (select *,1 as 'Counter' from dbo.TableStructure(@table));
union all
with tmpTable as (select *,2 as 'Counter' from dbo.TableStructure(firstTable.TableName));

解决方法

我想你只是想要cross apply

with ts as (
      select ts.*,1 as Counter
      from dbo.TableStructure(@table)
     )
select ts.*
from ts
union all
select ts2.*,2 as counter
from ts cross apply
     dbo.TableStructure(ts.tablename) ts2;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。