'Custom hook doesn't work when called on button click

I'm having trouble on finding what is wrong with this SQL statement. I'm using pyodbc latest and ODBC Driver 17 for SQL Server, here is the statement:

insert_sql = """MERGE VehicleDistanceReport trg
                            USING (VALUES (?, ?, ?))
                            src(
                            Distance,
                            Ic_Siparis_No,
                            Vehicle_Hour
                            )
                                    ON trg.Ic_Siparis_No = src.Ic_Siparis_No
                            WHEN MATCHED THEN
                                    UPDATE SET 
                                    Distance = src.Distance,
                                    Ic_Siparis_No = src.Ic_Siparis_No,
                                    Vehicle_Hour = src.Vehicle_Hour
                                    WHERE trg.NodeGroup LIKE N'%AĞIR%' OR trg.NodeGroup LIKE N'%MAKİNE%'
                            WHEN NOT MATCHED THEN
                                    INSERT(
                                        id,
                                        Record_No,
                                        Device_No,
                                        License_Plate,
                                        Inı
                                        Distance,
                                        Ic_Siparis_No,
                                        Vehicle_Hour
                                        )                                        
                                    VALUES(
                                        src.Distance,
                                        src.Ic_Siparis_No,
                                        src.Vehicle_Hour
                                        );"""

It says there is a syntax error near WHERE statement but the query seems to work in SQL server.



Solution 1:[1]

Your WHEN MATCHED clause is wrong, as the WHERE should be a condition. Also no pooint updating Ic_Siparis_No as it's the joining condition anyway

WHEN MATCHED AND trg.NodeGroup LIKE N'%A?IR%' OR trg.NodeGroup LIKE N'%MAK?NE%' THEN
    UPDATE SET 
    Distance = src.Distance,
    Vehicle_Hour = src.Vehicle_Hour

Don't be tempted to place this condition in the ON clause, it will cause incorrect results.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Charlieface