Generate a unique column sequence value based on a query handling concurrency

后端 未结 2 1700
半阙折子戏
半阙折子戏 2020-12-22 11:27

I have a requirement to automatically generate a column\'s value based on another query\'s result. Because this column value must be unique, I need to take into consideratio

相关标签:
2条回答
  • 2020-12-22 12:06

    You could look into using a TIME type instead of COUNT() to create unique values. That way it is much less likely to have duplicates. Hope that helps

    0 讨论(0)
  • 2020-12-22 12:08

    One possibility:

    Create a counter table:

    create table Counter (
       Id int identify(1,1),
       Name varchar(64)
       Count1 int
    )
    

    Name is a unique identifier for the sequence, and in your case name would be CustomerName-Month-Year i.e. you would end up with a row in this table for every Customer/Year/Month combination.

    Then write a stored procedure similar to the following to allocate a new sequence number:

    CREATE PROCEDURE [dbo].[Counter_Next]
    (
      @Name varchar(64)
      , @Value int out -- Value to be used
    )
    AS
    BEGIN
      set nocount on;
    
      declare @Temp int;
    
      begin tran
        -- Ensure we have an exclusive lock before changing variables
        select top 1 1 from dbo.Counter with (tablockx);
    
        set @Value = null; -- if a value is passed in it stuffs us up, so null it
    
        -- Attempt an update and assignment in a single statement
        update dbo.[Counter] set
          @Value = Count1 = Count1 + 1
        where [Name] = @Name;
    
        if @@rowcount = 0 begin
          set @Value = 10001; -- Some starting value
          -- Create a new record if none exists
          insert into dbo.[Counter] ([Name], Count1)
            select @Name, @Value;
        end
      commit tran
    
      return 0;
    END
    
    0 讨论(0)
提交回复
热议问题