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
I have simplified the logic a bit for generating
PackID
Add a new column(
identifier
) for identifying the code and use it forPackID
generation and for sequence useIdentity
columnTo check the working