WangKhar (Wa******@yahoo.com) writes:
create procedure getnextident @table sysname, @ident int output
as
begin
if not exists (select top 1 1 from myidents where name = @table)
insert into myidents values (@table, 0)
update myidents
set @ident = ident = ident + 1
where name = @table
end
now, (ignoring for now the use of reserved words) the problem is that
this is called frequently, from other procedures. Trouble is that the
calling procedures call it from within a transaction. We now have a
wickedly hot spot on this table, with frequent deadlocks.
Is there any relatively quick fix for this? Some locking hints or
whatever.
Deadlocks can usually be avoided by:
BEGIN TRANSACTION
SELECT @ident = ident FROM tbl (UPDLOCK) WHERE name = @table
UPDATE tbl SET ident = @ident WHERE name = @table
COMMIT TRANSACTION
However, if you have more work in the transaction, you will have lot of
blocking and not much concurrency in the system. And if you in some
procedures perform work before you come here, they might be blocking
other processes that aleady have an ident, and now wil block the other
prcoess.
The above is only really meaningful if you have busienss rules that
require consecutive series. Else you should move out the ident-generation
out of the transaction or use IDENTITY instead.
--
Erland Sommarskog, SQL Server MVP,
so****@algonet.se
Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp