Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MSSQL – Violation of UNIQUE KEY constraint

I’m getting this error message

IntegrityError: (2627, b"Violation of UNIQUE KEY constraint
‘XXXXX_TypeOfData_input_un’. Cannot insert duplicate key in object
‘XXXXX.TypeOfData_input’. The duplicate key value is (Processing Data,
Processing Data Name).DB-Lib error message 20018, severity
14:\nGeneral SQL Server error: Check messages from the SQL Server\n")

How to add unique constraint when insert?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code

INSERT INTO XXXXX.TypeOfData_input (TypeName, DataName)
        VALUES (%(TypeName)s, %(DataName)s)

My usual code for postgresql

INSERT INTO XXXXX.TypeOfData_input (TypeName, DataName)
            VALUES (%(TypeName)s, %(DataName)s) ON CONFLICT (TypeName, DataName) DO UPDATE NOTHING

>Solution :

We can use a MERGE statement to insert only if the record doesn’t already exist.

MERGE INTO XXXXX.TypeOfData_input AS target
USING (VALUES (%(TypeName)s, %(DataName)s)) AS source (TypeName, DataName)
ON target.TypeName = source.TypeName AND target.DataName = source.DataName
WHEN NOT MATCHED THEN
    INSERT (TypeName, DataName)
    VALUES (source.TypeName, source.DataName);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading