Microsoft SQL Server: Generate a sequence number, per day

后端 未结 5 1863
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 12:22

I\'m tasked to create an increasing sequence number per day for a project. Multiple processes (theoretically on multiple machines) need to generate this. It ends up as

5条回答
  •  花落未央
    2021-01-06 13:08

    You could do something like

    CREATE TABLE SequenceTableStorage (
        SequenceId bigint identity not null,
        SequenceDate date NOT NULL,
        OtherCol int NOT NULL,
    )
    
    CREATE VIEW SequenceTable AS
    SELECT x.SequenceDate, (CAST(SequenceDate AS VARCHAR(10)) + '_' + RIGHT('0000000000' + CAST(SequenceID - (SELECT min(SequenceId) + 1 FROM SequenceTableStorage y WHERE y.SequenceDate = x.SequenceDate) AS VARCHAR(10)), 10)) AS SequenceNumber, OtherCol
      FROM SequenceTableStorage x
    

    If you create an index on the SequenceDate and SequenceId, I don't think the performance will be too bad.

    Edit:

    The code above might miss some sequence numbers, for example if a transaction inserts a row and then rolls back (the identity value will then be lost in space).

    This can be fixed with this view, whose performance might or might not be good enough.

    CREATE VIEW SequenceTable AS
    SELECT SequenceDate, (CAST(SequenceDate AS VARCHAR(10)) + '_' + RIGHT('0000000000' + row_number() OVER(PARTITION BY SequenceDate ORDER BY SequenceId)
      FROM SequenceTableStorage
    

    My guess is that it will be good enough until you start getting millions of sequence numbers per day.

提交回复
热议问题