根据 Azure SQL 服务器中的名称查找多个列

Lookup multiple columns based on their names in Azure SQL Server

问题:我有 100 个 table 可以有不同的全名、出生日期、电子邮件和 ID 列名称。例如:Table 1 的全名是 Emp name,dob, work email 和 national id。 Table 2 可能有全名、出生日期、Wrk 电子邮件、NID 和 Table 3 可能有全名、出生日期、工作 Em、NatID 等等..10 个或更多不同 tables

全名 + DOB 被视为唯一列

我需要的是查询或自动方式来选择那些可能具有不同名称的列,并根据具有这些列及其值(全名、出生日期)的参考 table 查找这些列值, 工作邮箱, 身份证),如果我找到了匹配项

期望的结果:我需要检索找到匹配项的 table 名称、找到匹配项的列名、匹配的值和 return 如果未找到匹配项则“不匹配”

我尝试使用 INFORMATION_SCHEMA.COLUMNS,但还没有成功。任何帮助将不胜感激

如果是 10 table,那么大概您可以提前检查它们并知道您想要查看哪些列。接下来的挑战是将所有这些组合到一个查询中。你可以用一堆 UNIONS 来做,像这样:

select [Emp name] as Name, [dob] as DateOfBirth, [work email] as Email, [national id] as ID, 'Table1' as TableName
from Table1
UNION 
select [Full Nm] as Name, [date of birth] as DateOfBirth, [Wrk Email] as Email, [NID] as ID, 'Table2' as TableName
from Table2
UNION
select [Full Name] as Name, [birth date] as DateOfBirth, [Work Em] as Email, [NatID] as ID, 'Table3' as TableName
from Table3
UNION
--etc etc

请注意我们如何添加 TableName 列来告诉我们每个项目来自哪个 table。

要查询整个数据集,您需要将其声明为视图或类似的东西,或者将其嵌套在另一个 SELECT 中,如下所示:

select Name, DateOfBirth, Email, ID, TableName
from (
    select [Emp name] as Name, [dob] as DateOfBirth, [work email] as Email, [national id] as ID, 'Table1' as TableName
    from Table1
    UNION 
    select [Full Nm] as Name, [date of birth] as DateOfBirth, [Wrk Email] as Email, [NID] as ID, 'Table2' as TableName
    from Table2
    UNION
    select [Full Name] as Name, [birth date] as DateOfBirth, [Work Em] as Email, [NatID] as ID, 'Table3' as TableName
    from Table3
    UNION
    --etc etc
) giveitaname
WHERE [Name] = 'Joe Bloggs' and [DateOfBirth] = '01/Feb/1999'

我觉得你可以看看 INFORMATION_SCHEMA.COLUMNS。除非我没关注你,否则你一定能做到?

select c.COLUMN_NAME, IsNull(m.Found,'No Match') Matches
from INFORMATION_SCHEMA.COLUMNS c
outer apply (
    select column_name + ' is in ' + table_name Found
    from INFORMATION_SCHEMA.COLUMNS x
    where x.COLUMN_NAME =c.COLUMN_NAME and x.TABLE_NAME !=c.TABLE_NAME
)m
where c.table_name='MasterList'

创建您的 MasterList table,其中包含您想要在其他 table 中找到的所有列变体,然后这将列出数据库中的所有 table 列那场比赛。