[英]Comparing table with sql/tsql in SQL Server 2012
我在 SQL Server 2012 中有四个表: table1, table2, table3
和(结果/输出表) table4
table1
每天都会被截断并加载新数据。
table1
列col1, col2, col3
类似于table2
列col7, col18, col9
,和table3
列col9, col11, col7
,所以我们可以负载匹配行来回table2
和table3
问题
循环 table1 以检查每一行 (col1,col2,col3) 匹配 table2 中的任何行 (col7,col18,col9) 然后在 table4 中添加包含信息 table1.col1,table1.col2,table1.col3, table2.col6 的行, table3.col1,table3.col7 和一列指示其更新
如果 table1 中的行 (col1,col2,col3) 在 table2 中不存在,则在 table4 中添加包含信息 table1.col1,table1.col2,table1.col3, table2.col6,table3.col1,table3.col7 的行和一列来表示它的一个补充
如果 table2 中的行 (col7,col18,col9) 在 table1 中不存在,则在 table4 中添加包含信息 table1.col1,table1.col2,table1.col3, table2.col6,table3.col1,table3.col7 的行和一列来表示它是一个删除
返回 table4 作为结果
我们如何仅使用 SQL/TSQL 做到这一点?
本质上,您是在from
子句中寻找具有条件逻辑的full join
:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.