I want to create a procedure which would create a serial number using a stored procedure.
I have three tables:
Table 1:
create table ItemTypes
(
ItemTypeID int not null primary key,
ItemType varchar(30)
)
Table 2:
create table ItemBatchNumber
(
ItemBatchNumberID int not null primary key,
ItemBatchNumber varchar(20),
ItemType varchar(30),
)
Table 3:
create table ItemMfg
(
ManufactureID int not null primary key,
ItemBatchNumberID int foreign key references ItemBatchNumber(ItemBatchNumberID),
MfgDate datetime
)
For each Item Type there are several Item batch number.
Now, first 3 digit of serial no is xyz. 4 digit of serial no should be Item Type(e.g if Item type is 'b' then serial no should be xyzb).
5 digit of serial no should be like this:
In a day, for first Item batch number of a Item type, 5th digit should be 1 and it will remain 1 for that day.For the next different Item batch number it should be 2 and it will remain 2 for that day.
Same rule applied for next day and other item type.
e.g suppose 'b' Item Type has 3 Item batch number WB101,WB110,WB231. If today someone select WB110(Item batch number) of 'b' Item Type first then Serial No should be xyzb1 and it will remain xyzb1 for today for WB110. Now if someone select WR101 next then Serial No should be xyzb2 for today. Tomorrow which Item batch number of 'b' Item type will be selected first, for that batch number and that type serial no should be xyzb1. Same rule applied for other item type.
I have tried so far:
I have created a new table and stored data into that table and tried to check with columns of that new table.
Create table Gen_SN
(
ItemType varchar(10),
ItemBatchNumber varchar(10),
SerialNumber varchar(10),
mfgDate datetime
)
Alter procedure Gen_SerialNumber
(
@ItemType char(1),
@ItemBatchNumber varchar(30),
@Date datetime,
@SerialNumber varchar(20) out,
@fifthDigit int
)
AS
Begin
set @ItemType=(Select ItemType from ItemBatchNumber where ItemBatchNumber=@ItemBatchNumber)
Declare @SerialNumber1 varchar(20)
Set @SerialNumber1='xyz'+''+@ItemType+''+CAST( (Select COUNT(distinct ItemBatchNumber)from ItemBatchNumber
where ItemType=@ItemType) as varchar (10) )
Set @fifthDigit=SUBSTRING(@SerialNumber1,5,1)
if exists(Select SerialNumber from Gen_SN where SerialNumber=null or SerialNumber!=@SerialNumber)
set @fifthDigit=1
if exists(Select mfgDate,ItemBatchNumber from Gen_SN where mfgDate=@Date and ItemBatchNumber=@ItemBatchNumber)
Set @fifthDigit=1
else
set @fifthDigit=@fifthDigit+1
Set @SerialNumber=('xyz'+''+@ItemType+''+cast(@fifthdigit as varchar(2)))
Insert into Gen_SN values(@ItemType,@ItemBatchNumber,@SerialNumber,@Date)
END
I am new to SQL. 4rth digit of SN is generated correctly from my code. Please give me some idea on generating 5th digit and let me know if you have any doubt. Thanks in advance.