动态列合并更新

动态列合并更新

【问题】

I have one query, would be great if anyone can help me out on this.

In SQL, I have two tables with same column names. Want to query if there is any difference in the column values and if yes will update the values(in the first table) else if the row is not found will insert the row using the MERGE statement.
As of now, I have to mention all the columns in the tables and match by the values.

Eg: If the tables are like this:
Table1 (A,B,C,D…)
Table2 (A,B,C,D…)

The query would be like this :
MERBE INTO Table1 as TabA
USING (Select * from Table2) AS TabB
ON TabA.A=TabB.A
AND TabA.B=TabB.B
AND TabA.C=Tab.C
AND TabA.D=TabB.D


When Matched Then
Update
Set TabA.A=TabB.A,
, TabA.B=TabB.B
, TabA.C=TabB.C
, TabA.D=TabB.D
..
..
..
When NOT Matched Then
Insert Values (TabB.A,TabB.B,TabB.C, TabB.D..)
But I want the column names to be fetched dynamically so that everytime the column name changes or a new column is added , we dont have to rewrite the query(considering there are a lot of columns in the tables to be matched)

Please let me know if you want me to rephrase my sentence to make my statement clear .

【回答】

提问者需要将两表的一些列进行合并,将 B 表的一些列更新到 A 表。题目中已经给出了 MERGE 语句的写法,难点在于他需要合并的列数是动态的。

用存储过程拼接会很麻烦,这个问题可理解为将 B 表中一些字段值更新到 A 表,使用 SPL 其实可以直接更新:

A
1 =connect(“test”)
2 =A1.query(“select “+cols+” from B”)
3 =A1.update(A1,A)

A1:连接数据库。

A2:查询 B 表中要更新到 A 表的字段。

A3:执行更新。

在集算器中也可以通过序表操作合并两表并查看的结果:

A
1 =connect(“test”)
2 >A=A1.query(“select “+cols+” from A”).key(id)
3 >B=A1.query(“select “+cols+” from B”).key(id)
4 =[B,A].merge@uo(id)

A2、A3:查询 A 表、B 表,设置 id 为序表主键

A4:按 id 合并两表去重,保留 B 中的记录

A2

imagepng

A3

imagepng

A4

imagepng