0

I am trying to create a merge query for the same source table but having to update column values with variables

I tried some methods but syntax is always incorrect

Below is my query

cursor.execute('''merge Table_1 as t
                        using (SELECT'''+**BatchID**+''' as BatchID) as s
                        on t.BatchID=s.BatchID
                        when matched then
            UPDATE Machine_KPI set 
            shift_id=(select Shift_id from shift_details),
            Coupling_Fail_Count=?,
            System_time=GETDATE()''',
            (
            **val_couplingFailCount**,
            )
            '''when not matched then
            INSERT INTO Table_1 (MachineNo,BatchID,Shift_id,Coupling_Fail_Count,System_time) values(
            (select Machine_id from machine),
            ?,
            (select Shift_id from shift_details),
            ?,
            GETDATE(),
            )''',(
            **BatchID**,
            **val_couplingFailCount**,
            )

BatchID,val_couplingFailCount are some of the int variable which I am getting in python script . I am not sure how can I modify above Query to be perfect .

Alok Sharma
  • 95
  • 1
  • 12
  • Sample data and expected results would help. You need to use parameters `SELECT ? as BatchID` and honsetly I wouldn't use `MERGE` just use a conditional `UPDATE` and `INSERT` see https://sqlperformance.com/2020/09/locking/upsert-anti-pattern – Charlieface Jun 05 '23 at 15:46

0 Answers0