动态列合并更新

提问者寻求在SQL中动态比较并更新两个表的列值。当前使用MERGE语句,但希望在列名变化或新增列时无需手动修改查询。回答建议使用集算器的SPL语言,通过连接数据库、查询所需更新的字段,然后执行更新操作,以实现动态合并和更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【问题】

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

A3

A4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值