create procedure up_get_table_key( @table_name varchar(50), @key_value int output)asbegin begin tran declare @key int --initialize the key with 1 set @key=1 --whether the specified table is exist if not exists(select table_name from table_key where table_name=@table_name) begin insert into table_key values(@table_name,@key) --default key vlaue:1 end -- step increase else begin select @key=key_value from table_key with (updlock) where table_name=@table_name set @key=@key+1 --update the key value by table name update table_key set key_value=@key where table_name=@table_name end --set ouput value set @key_value=@key --commit tran commit tran if @@error>0 rollback tranend
注意在查询的时候我使用了updlock,我在检索时对该行加锁,updlock的优点是允许用户读取数据(不阻塞其它事务)并在以后更新数据,同时确保 自从上次读取数据后数据没有被更改。也就是说,我在本次事务调用中取到key值之后,直到更新该数据之后,锁可以保证了key值不会更改,确实不会的会话 不会拿到相同的key值。