Monday, March 26, 2012

INSERT violates primary key. Which way out?

Hi,
newbie question. I have an plain INSERT INTO clause:

BEGIN TRAN
INSERT INTO BILLS
SELECT
BillCode,
MyUNID
FROM DPA_BILLS
WHERE ErrorCode IS NULL
COMMIT TRAN

The original DPA_BILLS table can hold (and actually holds) rows with
non-unique values of BillCode, which is primary key in the destination
BILLS table. An acceptable behaviour would be to update the existing
row. Given that these constraints have to be kept, which is the best
way to act? Shall I process in advance my source table, resolving
foreing key conflicts, or shall I rely on some error handling in the
INSERT clause?

Thanx> Shall I process in advance my source table, resolving
> foreing key conflicts

Depends on what logic you want to apply. If it's something you can put
into code then do it wherever it is easiest. Error handling isn't the
answer because the whole of the insert fails on error, not just the
duplicate row(s).

--
David Portas
SQL Server MVP
--|||BTW you don't need BEGIN TRAN ... COMMIT TRAN. A transaction is
implicit for a single DML statement.

--
David Portas
SQL Server MVP
--

No comments:

Post a Comment