问题描述
我使用的是 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;