Your MERGE statement appears conceptually correct but with potential errors as per Snowflake syntax and logic:
-
Typo in WHEN NOT MATCHED clause: You have two WHEN NOT MATCHED clauses that insert the same values. This seems redundant and will cause an error since only one WHEN NOT MATCHED block is allowed. Determine the correct logic for when a record is not matched and include only one WHEN NOT MATCHED block that represents this logic correctly.
-
Reference to CustomerID in the INSERT statements: In the INSERT statements within the WHEN NOT MATCHED blocks, you reference CustomerID, but it's not clear where this is coming from as it’s not selected in the sub-query defined in the USING clause. Ensure all values you are inserting, including CustomerID, are either constants, derived in the SELECT statement within the USING clause, or part of the target table’s columns if applicable. You might need to modify your sub-query to include this field if it's meant to be dynamically derived from your data sources.
Given the above considerations, a corrected version of your MERGE statement may look like this:
MERGE INTO VehicleDeviceMapping_kipi AS V
USING (
SELECT DISTINCT
de.DeviceID AS rsndeviceid,
tupd.DeviceID,
v1.VehicleID AS GQSIIIVehicleID,
-- Ensure you have the `CustomerID` or any other required field in your SELECT if needed for INSERT
'YourCustomerIDValueOrReferencedFieldHere' as CustomerID
FROM tblUDPDataToProcessforQSConPktDtls AS tupd
LEFT JOIN device_kipi AS de ON de.DeviceSerialNumber = tupd.rsnserialnumber
LEFT JOIN VehicleDeviceMapping AS v1 ON v1.DeviceID = tupd.DeviceID
QUALIFY ROW_NUMBER() OVER (PARTITION BY tupd.DeviceID ORDER BY v1.VehicleID) = 1
) SRC
ON V.DeviceID = SRC.rsndeviceid
WHEN MATCHED AND V.VehicleID != SRC.GQSIIIVehicleID THEN -- Adjust this condition based on your actual logic
UPDATE SET
V.Active = 0,
V.DeletedBy = 1,
V.DeletedOn = CURRENT_TIMESTAMP()
WHEN NOT MATCHED THEN -- Maintain one WHEN NOT MATCHED block with your correct logic
INSERT (
VehicleID,
DeviceID,
CreatedBy,
CreatedOn,
CustomerID,
Active
) VALUES (
SRC.GQSIIIVehicleID,
SRC.rsndeviceid,
1, -- Assuming 1 is your CreatedBy value, else replace accordingly
CURRENT_TIMESTAMP(),
SRC.CustomerID, -- Ensure this is correctly referenced based on your SELECT
1
);
Make sure to adjust the logic and fields according to your requirements, particularly for the condition in WHEN MATCHED clause and properly sourcing the CustomerID in the sub-query inside the USING clause.