首页 > 解决方案 > 将表与 SQL Server 2012 中的 sql/tsql 进行比较

问题描述

我在 SQL Server 2012 中有四个表:table1, table2, table3和一个(结果/输出表)table4

  1. table1每天都会被截断并加载新数据。

  2. table1columnscol1, col2, col3类似于table2columnscol7, col18, col9table3columns col9, col11, col7,所以我们可以加载匹配行来回table2table3

问题

循环 table1 以检查每一行 (col1,col2,col3) 是否匹配 table2 中的任何行 (col7,col18,col9) 然后在 table4 中添加包含信息 table1.col1,table1.col2,table1.col3,table2.col6 的行, table3.col1,table3.col7 和一列指示其更新

返回 table4 作为结果

我们如何仅使用 SQL/TSQL 来做到这一点?

标签: sqlsql-servertsql

解决方案


本质上,您正在寻找子句full join中的条件逻辑:from

insert into table4
select
    t1.col1,
    t1.col2,
    t1.col3,
    t2.col6,
    t3.col1,
    t3.col7,
    case 
        when t2.col7 is null then 'insert'
        when t1.col1 is null then 'delete'
        else 'update'
    end action
from table1 t1
full join table2 t2 on t1.col1 = t2.col7 and t1.col2 = t2.col8  and t1.col3 = t2.col9
full join table3 t3 on t1.col1 = t3.col9 and t1.col2 = t2.col11 and t1.col3 = t3.col7

目前还不清楚,你想用table3. 可能,您想要left join它而不是full join,并检查前面两个表的条​​件,例如:

left join table t3
    on  t3.col9  = coalesce(t1.col1, t2.col7)
    and t3.col11 = coalesce(t1.col2, t2.col8)
    and t3.col7  = coalesce(t1.col3, t2.col9)

推荐阅读