开发者

Atomic SQL Operation: unsure of approach (insert/update depending on existing data)

A table contains something like the following:

   ID: 4 
 DATE: 040910 
COUNT: 42

If the ID and DATE already exist in the table, increase the count by one. If the specific ID and DATE do not already exist, create with a count of 1. 'ID' is not unique - it may be duplicated in the table as long as the date code changes.

Everytime I think of a solution, it seems to incur possible race conditions. I thought about BEGIN/END transaction, but that doesn't seem 100% reliable either. I can't just do the insert and if it fails then update unless I merge the ID field into DATE and make it a unique column.

Ideas?

Edit: I've just thought of this:

INSERT INTO table (...) VALUES (...)
WHERE NOT EXISTS (SELECT 1 FROM table WHERE table.id == x AND table.date == y)

UPDATE table SET count = count + 1 WHERE table.id == x AND table.date == y

So the update is always executed, but the insert depends on the current value of the table, but I'开发者_运维技巧m concerned that still 2 records could appear with the same id & date.


What is wrong with transactions? Unless there's a bug in SQL Server, they will work as described. You can also set the ISOLATION LEVEL of a transaction to suit your needs.

BEGIN TRANSACTION;

UPDATE YourTable
   SET Count = Count + 1
 WHERE ID = X AND Date = Y;

IF @@rowcount = 0
    INSERT INTO YourTable (ID, Date, Count)
    VALUES (X, Y, 1);

COMMIT TRANSACTION;

You should also have a unique constraint on both columns (ie: UNIQUE(ID, DATE))

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜