4

Very occasionally on a multi-user system with SQL Server 2008 R2 I am getting errors like "Cannot insert duplicate key row in object 'dbo.pages' with unique index 'UX_pages_pageid_siteid'. The duplicate key value is (141, 4385).". That index does indeed enforce uniqueness but this is a single statement that should guarantee uniqueness as far as I know:

INSERT INTO pages (pageid, siteid) 
    SELECT (SELECT ISNULL(CAST(MAX(ABS([pageid])) AS int), 1000) + 1 
    FROM pages 
    WHERE siteid = 4385), 4385;

I know this would be cleaner with an auto-incrementing identity but I can't change the schema.

The statement is executing inside o_Connection.BeginTrans() and the database has is_read_committed_snapshot_on = 1 which I suspect is involved but I cannot reproduce the problem (e.g. by amending this blog with INSERT INTO tblPapers (Url) SELECT MAX(url) + 'z' FROM tblPapers) or find any explanation in locking documentation.

Is it really the case that the nested SELECT may provide out-of-date data even though it is in the same statement and so changing the code to be FROM pages (UPDLOCK) is the correct fix?

5
  • What datatype is padeid? And by the way, what result do you get when you run SELECT ISNULL(CAST(MAX(ABS([pageid])) AS int), 1000)?
    – potashin
    Jan 27, 2015 at 13:48
  • pageid is int allowing nulls and the select happily returns an integer (150) at the moment. Jan 27, 2015 at 13:58
  • With Sql Server 2012, you could probably solve this with a sequence. I know your stuck on 2008R2 right now, just something to keep in mind in the future. msdn.microsoft.com/en-us/library/ff878091%28v=sql.110%29.aspx Jan 27, 2015 at 14:13
  • 1
    This error is almost certainly a result of concurrency. This is one of the main reasons trying to roll your own identity is a problem. You say you can't change the schema so you are going to be stuck with this unless you get very creative or upgrade to a newer version of sql.
    – Sean Lange
    Jan 27, 2015 at 14:40
  • 1
    Thanks for the comments so far. We have now got this to occur on the test server every few tries but not when the (UPDLOCK) that Mark S. Rasmussen's blog suggests is included so are going with that for now. Jan 27, 2015 at 14:51

1 Answer 1

1

Maybe not scalable but try

INSERT INTO pages with (tablock) (pageid, siteid) 
    SELECT (SELECT ISNULL(CAST(MAX(ABS([pageid])) AS int), 1000) + 1 
    FROM pages 
    WHERE siteid = 4385), 4385;

I just read the comments - if (UPDLOCK) workds then stay with that

1
  • Thanks; I'll accept this as the answer rather than adding my own. Jan 28, 2015 at 11:06

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.