开发者

PK Violation on a history table

This is in SQL Server 2005.

I have an address table:

dbo.Address
(
  AddressID INT IDENTITY(1, 1) PRIMARY KEY
  LastUpdateBy VARCHAR(30)
  <bunch of address columns>
)

I also have a history table:

dbo.AddressHistory
(
  AddressID INT,
  AsOf DATETIME,
  UpdateBy VARCHAR(30)
  <all the address columns>
  CONSTRAINT PK_dbo_AddressHistory PRIMARY KEY CLUSTERED (AddressID, AsOf)
)

I have a trigger on dbo.Address to create history entries on both INSERT and UPDATE which will basically do this:

INSERT INTO dbo.AddressHistory(AddressID, AsOf, UpdateBy, <address columns>)
SELECT AddressID, CURRENT_TIMESTAMP, @UpdateBy, <address columns>
FROM INSERTED
开发者_运维百科

But, every once in while, I'll get a PK violation on dbo.AddressHistory complaining about a duplicate PK being inserted. How is this possible if part of the PK for AddressHistory is the current timestamp of the insertion?

Even executing this will insert two rows into the history table successfully:

INSERT INTO dbo.Address
(LastUpdateBy, <address columns>)
SELECT 'test', <address columns>
FROM dbo.Address
WHERE AddressID < 3

And the only update sproc I have for the dbo.Address table will update a row for a given AddressID. So it should only be updating one row at a time. My insert sproc only inserts one row at a time as well.

Any idea what conditions cause this to occur?


Based on your description two concurrent executions of the stored procedure with the same parameter would seem likely.

datetime only has a precision of 1/300 second so conflicts can occur if these executions happen very close together.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜