SQL Server:防止在循环中插入期间锁定表

时间:2014-02-12 09:28:08

标签: sql-server transactions cursor locking

我有一笔交易:

BEGIN TRANSACTION

OPEN cursor
FETCH NEXT FROM cursor INTO @i

WHILE @@FETCH_STATUS = 0
BEGIN
    INSERT INTO BigTable () VALUES ()
    WAITFOR DELAY '00:01:00';

    FETCH NEXT FROM cursor INTO @i
END

COMMIT;

问题是,该事务锁定了BigTable整个循环和WAITFOR DELAY时间。

如何防止锁定,表格仅在INSERT期间被锁定?

2 个答案:

答案 0 :(得分:1)

请在光标处添加“FOR LOCAL STATIC READ_ONLY FORWARD_ONLY”:

DECLARE MY_CURSOR CURSOR FOR  LOCAL STATIC READ_ONLY FORWARD_ONLY
SELECT columnname...
FROM table-name

BEGIN TRANSACTION

OPEN cursor
FETCH NEXT FROM cursor INTO @i

WHILE @@FETCH_STATUS = 0
BEGIN
    INSERT INTO BigTable () VALUES ()
    WAITFOR DELAY '00:01:00';

    FETCH NEXT FROM cursor INTO @i
END

COMMIT;

答案 1 :(得分:1)

  

事务锁表

事务不会锁定,它会锁定插入的行。锁定一直持续到交易结束,这是不可协商的。

更好的问题是“如何在插入过程中读取数据?”答案当然是在读者中使用snapshot isolation