【问题标题】:SQL: Apply and union table function recursivelySQL:递归应用和联合表函数
【发布时间】:2021-01-19 08:29:12
【问题描述】:

我正在使用 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));

【问题讨论】:

标签: sql sql-server recursion table-functions multiple-input


【解决方案1】:

我想你只是想要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;

【讨论】:

    猜你喜欢
    • 2011-04-12
    • 2010-10-07
    • 1970-01-01
    • 2010-10-03
    • 2016-02-24
    • 1970-01-01
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多