Multi-row insert with unique index
Hi,
I am working on a SQL 2005 database 'contact' table with a unique identity key, id, and a unique index on the partner_id field, as below.
CREATE TABLE [dbo].[contact](
[id] [int] IDENTITY(1,1)
NOT
NULL,
[partner_id] [int]
CONSTRAINT [PK_contact]
PRIMARY
KEY
CLUSTERED
(
[id] ASC
)
WITH
(PAD_INDEX
=
OFF,
STATISTICS_NORECOMPUTE
=
OFF,
IGNORE_DUP_KEY
=
OFF,
ALLOW_ROW_LOCKS
=
ON,
ALLOW_PAGE_LOCKS
=
ON,
FILLFACTOR
= 90)
ON [PRIMARY],
CONSTRAINT [IX_contact_partner_id]
UNIQUE
NONCLUSTERED
(
[partner_id] ASC
NOT
NULL
CONSTRAINT [DF_contact_partner_id]
DEFAULT
((0)),
)
WITH
(PAD_INDEX
=
OFF,
STATISTICS_NORECOMPUTE
=
OFF,
IGNORE_DUP_KEY
=
OFF,
ALLOW_ROW_LOCKS
=
ON,
ALLOW_PAGE_LOCKS
=
ON,
FILLFACTOR
= 90)
ON [PRIMARY]
)
ON [PRIMARY]
Currently, when an individual record is inserted, if partner_id still has the default 0 value, a trigger then updates the partner_id field to be -1 times the id field, to
maintain uniqueness.
I am wanting to perform a multiple row insert to this table, but, not surprisingly, get the error message
"Violation of UNIQUE KEY constraint 'IX_contact_partner_id'"
The trigger obviously does not fire until after the multi-row insert has been attempted, with all the partner_id fields set to 0.
What I find odd is that if the multi-row insert is attempted using an ODBC connection from Access, then it works fine. Is Access known to perform multi-row inserts to SQL as a sequence of single record inserts?
As a supplementary question can anyone think of a way of doing this using SQL, without radically changing the database design?
Thanks
February 26th, 2011 6:53am