Dynamically Column UPDATE & MERGE
【Question】
I have a 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 every time the column name changes or a new column is added, we don’t 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.
【Answer】
You need to MERGE columns with same names from two tables by updating table A’s values with corresponding ones in table B or inserting table B’s rows to table A. You’ve already done the MERGE part but you need to fetch column names dynamically.
Achieving the requirement with stored procedure is inconvenient. If we rephrase your requirement, it is actually updating table B’s certain field values to table A. So we can directly do the update with esProc SPL (Structured Process Language):
A |
|
1 |
=connect(“test”) |
2 |
=A1.query(“select “+cols+” from B”) |
3 |
=A1.update(A1,A) |
A1: Connect to the database.
A2: Get table B’s fields used to update table A.
A3: Do the update.
You can also merge columns from table A and those from table B to achieve your goal with esProc:
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: Get columns from table A and those from table B through primary key id.
A4: Perform MERGE and remove duplicate values but retain table B’s records.
A2:
A3:
A4:
SPL Official Website 👉 https://www.scudata.com
SPL Feedback and Help 👉 https://www.reddit.com/r/esProcSPL
SPL Learning Material 👉 https://c.scudata.com
SPL Source Code and Package 👉 https://github.com/SPLWare/esProc
Discord 👉 https://discord.gg/cFTcUNs7
Youtube 👉 https://www.youtube.com/@esProc_SPL