开发者

How to block inserts in SQL Server from the same user only - serializable isolation

I have the following table

CREATE TABLE [dbo].[Test]([Id] [int] NOT NULL,[Name] [varchar](50) NOT NULL,
CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)
WITH (PAD_INDEX = OFF, 
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY=OFF,
ALLOW_ROW_LOCKS=ON,
ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

CREATE NONCLUSTERED INDEX [IX_Test] ON [dbo].[Test] 
(
   [Name] ASC
)
WITH (PAD_INDEX  = OFF, 
STATISTICS_NORECOMPUTE  = OFF, 
SORT_IN_TEMPDB = OFF, 
IGNORE_DUP_KEY = OFF, 
DROP_EXISTING = OFF, 
ONLINE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO

Now I want to prevent inserts from the same user (but different session) until the session in progress has completed. For example, if user John starts the session with insert, I want his other session (with insert, too) to be blocked until the first session completes. In other words, I need to block inserts that do not yet exists.

So i created the following two scripts to run them in separate Management studio query windows: First (user John; waitfor is in first query only to be able to simulate the problem):

begin tran

select COUNT(*)
from Test with(updlock,holdlock)
where Name = 'John'

waitfor delay '00:00:05'

insert into Test(Id,Name)
select isnull(MAX(Id) + 1,1),'John' from Test

commit tran

Second (user Peter):

begin tran

select COUNT(*)
from Test with(updlock,holdlock)
where Name = 'Peter'

insert into Test(Id,Name)
select isnull(MAX(Id) + 1,1),'Peter' from Test

commit tran

Now if I start first query from the first Management Studio query window and then start second query in the second query window before the first has completed, the second query is blocked until the first one completes. Well, maybe this is how this is supposed to work, but it is not something I want开发者_开发百科: I want second session to be blocked only if the same user wants to insert data. In my example, John starts to insert data, but Peter (second query) is blocked until John's insert completes.

Is it possible to instruct sql server (with locking hints, I suppose) to block second query only if the same user tries to insert data? For example, if John starts to insert data to only block John's other sessions, but not Peter's sessions?


In this case you probably need to set up a flag in the DB which is user specific (create table with user_id and is_writting flag). When you start to write in the table first check whether the flag is set -when not update the flag and write to the table. After the write finished unset the flag.

This is how I would probably solve this. But I'm open to any other ways ;)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜