1

I have a source table that drives the content of a second table. I have two or more processes that will be running for this (with different additions to the where clause). All essentially use the statement below. Somehow I am getting duplicates in the destination table. I am not currently specifying an isolation level - or any locking hints. The SQL Server is running 2005 which is something I cannot change (I know 2008's MERGE would probably be applicable).

INSERT INTO tableDst 
    (PK, ...)
SELECT src.PK, ...
FROM tableSrc src
LEFT JOIN tableDst dst ON src.PK = dst.PK
WHERE dst.PK IS NULL

The two tables are in different databases. Both databases are on the same instance on the same server, so cross-database statements such as this are possible.

What isolation level or locking hints do I need to make this work in an atomic fashion, so duplicates are prevented? Do I need to wrap it in a transaction?

1 Answer 1

1
INSERT INTO tableDst 
    (PK, ...)
SELECT src.PK, ...
FROM tableSrc src WITH (UPDLOCK, HOLDLOCK)
LEFT JOIN tableDst dst ON src.PK = dst.PK
WHERE dst.PK IS NULL

That is equivalent to SERIALIZABLE, it will block reads to the source table selected rows.

Without knowing your precise scenario and testing not sure if you might also need:

INSERT INTO tableDst 
    (PK, ...)
SELECT src.PK, ...
FROM tableSrc src WITH (UPDLOCK, HOLDLOCK)
LEFT JOIN tableDst dst WITH (UPDLOCK, HOLDLOCK) ON src.PK = dst.PK
WHERE dst.PK IS NULL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.