replace a computed column with a logic that works

2019-09-11 14:43发布

I have a table called tblPacks.

CREATE TABLE [dbo].[tblPacks]
    (
        [ID] [int] NOT NULL,
        [BatchNumber] [varchar](30) NULL,
        [PackID] VARCHAR(50),
        [Status] [int] NULL
    )

And a stored procedure spInsertPacks.

CREATE PROCEDURE spInsertPacks
@ID INT,
@BatchNumber VARCHAR(30),
@Count INT
AS 
BEGIN
INSERT INTO tblPacks 
Values
    (
        @ID,
        @BatchNumber, 
        CONVERT([varchar](50),
        'PK'+
            case 
                when len(@ID)<=(3) then CONVERT([varchar](20),right((0.001)*@ID,(3)),0) 
                else CONVERT([varchar](20),@ID,0) 
            end,0),0)
END

If ID of data type INT inserted in an order like 1,2,3,4,5... the above logic works fine. But there is no restriction for a user to enter random numbers. I want a stored procedure to generate PackID(PK001,PK002..) sequence in order, irrespective of @ID and ID. Cannot be an identity Column. How can I do that? Actually This PackID is a barcode If barcode already existed for Pack then that sequence may not be same with the sequence we used and Newly generated barcodes which we are generating will be in seuquence PK001 Sample Output:-

ID BatchNumber PackID     Status
 1    b1           PK001    0
 1    b2           Pk002    0
 5    b7           ABC768   0
 3    b2           PK003    0

1条回答
Juvenile、少年°
2楼-- · 2019-09-11 15:12

I have simplified the logic a bit for generating PackID

Add a new column(identifier) for identifying the code and use it for PackID generation and for sequence use Identity column

CREATE TABLE [dbo].[tblPacks]
  (
     Iden_ID       INT IDENTITY(1, 1),
     [ID]          [INT] NOT NULL,
     [BatchNumber] [VARCHAR](30) NULL,
     [Identifier]  [VARCHAR](50),
     [PackID] AS [Identifier]
        + CASE
            WHEN Iden_ID <= 999 THEN RIGHT('00' + CONVERT(VARCHAR(3), ID), 3)
            ELSE CONVERT([VARCHAR](20), ID, 0)
          END,
     [Status]      [INT] NULL
  ) 

To check the working

INSERT INTO [dbo].[tblPacks]
            ([ID],identifier,[BatchNumber],[Status])
VALUES      (1,'pk','bat',1)

SELECT *
FROM   [tblPacks] 
查看更多
登录 后发表回答