插入和选择时锁定表格

时间:2013-06-07 01:13:54

标签: c# sql-server

我正在创建一个asp.net站点,用户提交一些插入表1的数据,然后运行查询以获取随后从表1创建的条目的ID,然后将该ID插入表2.问题是,如果有人恰好同时提交,我很容易得到不正确的数据。我假设可以锁定表1,直到数据已插入表2,但我不确定如何做到这一点。谁能提供一些指导?我的所有代码都在C#Code Behind文件中。我读到你可以用下面的东西来做,但如果有效,它是如何解锁的?

UPDATE table1 WITH (rowlock)

1 个答案:

答案 0 :(得分:1)

您的ADO可以调用的示例proc。

/*
create table a (id int identity(1,1) primary key, name varchar(max))
create table b (id int identity(1,1) primary key, ParentID int)
GO

create proc Test as
begin
    declare @parentId int
    begin tran
    begin try
        insert into a(name) values('abc')
        select @parentId = SCOPE_IDENTITY()
        select 'ScopeID',@parentID
        insert into b(ParentID) values(@parentid)
        --Uncomment this to see the rollback happen
        --raiserror ('Testing what will happen if an error occurred to make sure rollback works.',
        --       16, -- Severity.
        --       1 -- State.
        --       );
        commit tran
    end try
    begin catch
        rollback tran
    end catch
end
go
*/

truncate table a --TRUNCATE RESET IDENTITY SEED VALUES (UNLIKE DELETE)
truncate table b
exec Test
select * from a
select * from b