如何比较结构不同的两个表A和B

时间:2019-07-17 15:10:16

标签: sql-server msbi

如何比较结构不同的两个表A和B,我需要检查表B(8列中的任何一个)中是否存在表A(2列)中的数据?什么是有效的方法? >

1 个答案:

答案 0 :(得分:2)

如果以下查询返回一行,则A的两列之一的值至少存在于B的八列之一

private void Application_SheetChange(object Sh, Range Target)
{
        log.Info("Reached Application_SheetChange....!!!");

        Excel.Worksheet sheet = (Excel.Worksheet)Sh;

        string changedRange = Target.get_Address(Excel.XlReferenceStyle.xlA1);

    var input = Target.Value;

}

// excelRange.Value = contains the specific row and column
// below line inserts data into cell
 excelRange.Value = qrcodescanneddata;
 currentSheet.Cells[insertAtIndex, i] = finalResultString;

在Transact-SQL中,您还可以在IN列表中指定表达式,而不仅仅是常量。这样可以使该变体短一些

SELECT TOP 1 B.Id
FROM B
WHERE
    EXISTS (SELECT * FROM A WHERE
        B.c1 = A.c1 OR B.c2 = A.c1 OR B.c3 = A.c1 OR B.c4 = A.c1 OR
        B.c5 = A.c1 OR B.c6 = A.c1 OR B.c7 = A.c1 OR B.c8 = A.c1 OR
        B.c1 = A.c2 OR B.c2 = A.c2 OR B.c3 = A.c2 OR B.c4 = A.c2 OR
        B.c5 = A.c2 OR B.c6 = A.c2 OR B.c7 = A.c2 OR B.c8 = A.c2)

另请参阅:IN (Transact-SQL)

或者您可以反转两个表

SELECT TOP 1 B.Id
FROM B
WHERE
    EXISTS (SELECT * FROM A WHERE
        A.c1 IN (B.c1, B.c2, B.c3, B.c4, B.c5, B.c6, B.c7, B.c8) OR
        A.c2 IN (B.c1, B.c2, B.c3, B.c4, B.c5, B.c6, B.c7, B.c8)
    )

另一个变种是

SELECT TOP 1 A.Id
FROM A
WHERE
    EXISTS (SELECT * FROM B WHERE
        A.c1 IN (B.c1, B.c2, B.c3, B.c4, B.c5, B.c6, B.c7, B.c8) OR
        A.c2 IN (B.c1, B.c2, B.c3, B.c4, B.c5, B.c6, B.c7, B.c8)
    )

如果查询速度较慢,则值得测试不同的变体,以查看其性能是否更高。 SELECT TOP 1 A.Id FROM A CROSS JOIN B WHERE A.c1 IN (B.c1, B.c2, B.c3, B.c4, B.c5, B.c6, B.c7, B.c8) OR A.c2 IN (B.c1, B.c2, B.c3, B.c4, B.c5, B.c6, B.c7, B.c8) 子句对性能很重要,因为一旦找到匹配项,查询执行就会停止。