SQL 2008 R2 and the database has snapshot isolation on if that matters.
A third party executes this stored procedure in a multi-threaded application and one of my upsert queries fails to work completely. Example:
BEGINTRANSACTION CampaignStats
MERGE dbo.tblStatsHourlyCampaignWITH (HOLDLOCK)AS stat_target
USING (SELECT @iQueueID, @ReportDate)AS stat_source(QueueID, ReportDay)
ON (stat_target.QueueID= stat_source.QueueIDAND stat_target.ReportDay= stat_source.ReportDay)
WHENNOT MATCHEDTHEN
INSERT (QueueID, ReportDay,[EmailsSent])
VALUES (stat_source.QueueID, stat_source.ReportDay, @num)
WHENMATCHEDTHEN
UPDATESET [EmailsSent]= stat_target.[EmailsSent]+ @num;
COMMITTRANSACTION CampaignStats
The query executes and updates a table with the count represented by @num and then executes the query above. The query without error is ignored and nothing gets created even though it’s a new QueueID and ReportDay but then half way through the execution it will create the record and out of being executed 100 times will only count around 40 or 50. Its hard to explain because this behavior is so strange? Why won’t it create the missing row when there is no match the first time its ran but it will after its ran about 30 to 50 times and then it works properly.
I even tried eliminating the MERGE and used the old style UPSERT method with the exact same results. The dbo.tblStatsHourlyCampaign has a index on QueueID and ReportDay and if I run it just once it works. Its when its under load. I can provide you anything I’m just stuck!