简体   繁体   中英

Configurable Serial Tracking Number Generation

I am working on a C# .NET (& TSQL) based project which requires generation of configurable serial tracking numbers which depend on the data it contains.

Background

To elaborate, the software is used to track vehicles entering a factory. Each vehicle is assigned an RFID card and a tracking number. The tracking number is based on first of many warehouses to which the truck is headed. The admin can configure the format of the numbers for each warehouse. This is typically as follows: #YYYYMMDD-XX002211 where XX is a prefix unique to each warehouse. This number restarts from 1 whenever the month changes.

At the time of master (vehicle + RFID card details) creation, the tracking number is null . Once the first line (warehouse details) is added the system generates a tracking number and assigns it to the master. So, until the time a line is added, the tracking number field can have duplicates ie many records with null .

The problem

The code to generate the tracking number is written in C# and uses SQL transactions, however there have been infrequent collisions in the tracking which causes the system to be unstable. I did more research into TSQL Transactions to find the Isolation Level settings however I have not been successful with them.

Solution?

I have tried the following approaches:

  • Check in the master table for a possible duplicate before updating
  • Use Repeatable Read isolation level to ensure data isn't updated during the transaction execution

Should I?

  • Move the whole thing to a Stored Procedure?
  • Start a daemon which is responsible for the number generation, ensuring sequence by a single threaded execution

Thanks for your help!

In case of simplicity, I would suggest you to get a single Stored Procedure to update and get the sequence number, then do other formatting with C#

CREATE PROCEDURE GetSequenceOfWareHouse
    @WareHouse char(2)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @Result table (Sequence int)

    BEGIN Tran
        UPDATE SequenceTable SET Sequence = Sequence + 1 
            OUTPUT inserted.Sequence INTO @Result 
        WHERE WareHouse = @WareHouse AND Month = YEAR(GETDATE()) * 100 + MONTH(GETDATE())

        IF NOT EXISTS(SELECT * FROM @Result)
            INSERT SequenceTable (Sequence, WareHouse, Month) 
                OUTPUT inserted.Sequence INTO @Result 
            VALUES (1, @WareHouse, YEAR(GETDATE()) * 100 + MONTH(GETDATE()))

    COMMIT Tran

    SELECT Sequence FROM @Result

END
GO


CREATE Table SequenceTable
(
    Sequence int,
    WareHouse char(2),
    Month int,

    unique (Sequence, WareHouse, Month)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM