【发布时间】: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));
【问题讨论】:
-
您使用的是哪个 dbms?
-
SQL Server 管理工作室 18
-
您是否被锁定在表函数中?使用 CTE 是我以前做过这些事情的方式。 stackoverflow.com/questions/49939839/… - 这就是我使用 Oracle 的方式。 SQL Server 并没有太大的不同。stackoverflow.com/questions/23336520/…
标签: sql sql-server recursion table-functions multiple-input