sql - SQL: Apply and union table function recursively
问题描述
I'm using SQL Server Management Studio 18.
I have a function that takes a table name as a parameter and outputs a table with info about other tables that have the same columns in it. Each table has a different amount of columns (that are also in other tables or not). The output is column names, table names and subject. This works. I want to apply the same function to all tables that are in the result set of the first table I applied the function to, and union it with each other.
I know what I am doing wrong (dbo.TableStructure(firstTable.TableName)) doesn't work because the function is made for only 1 parameter and not multiple. But I don't know what to change to make it right. The code of the function:
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)))
The code of applying the function:
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;
推荐阅读
- javascript - 使用 RNFetchBlob.fs.cp 和从 react-native-document-picker 获取的 uri 导致错误
- sql-server - 如何将行转换为单列?
- python - 读取多个 csv 文件(大小 mxm)并加载为 n 维数组(大小 nxmxm)(不连接)
- python - 从 GoogleDriveFile pydrive 的内容中获取类似对象的文件
- node.js - 关于如何从另一个 nodejs 脚本调用无服务器 shell 命令的任何想法
- apigee - Apigee 休息端点路径映射到自定义路径
- apache-poi - 如何超链接包含 Excel 特殊字符的 SMB 文件
- mysql - REST API 的服务器与无服务器
- angular - 选项卡单击时的角度完整日历初始化问题
- c# - C# 控制台应用程序的负载均衡器