I'm developing a system that manages work orders for vehicles. The ID of work orders is composed as follows: OT-001-16
.
Where OT-
is a string, 001
is the counter, followed by -
character and finally the number 16
is the current year.
Example:
If the current year is 2018, the ID should be OT-001-18
.
The problem is when the year changes, the counter must restart from 001
. I have a stored procedure to do that, but i think i'm doing a lot more work.
This is my stored procedure code:
CREATE PROCEDURE ot (@name varchar(100), @area varchar(100), @idate varchar(100), @edate varchar(100))
AS
BEGIN
SET NOCOUNT ON;
DECLARE @aux varchar(100);
DECLARE @aux2 varchar(100);
DECLARE @aux3 int;
DECLARE @aux4 varchar(100);
SELECT @aux = id_workorder FROM idaux;
IF (@aux IS NULL)
SET @aux = CONCAT('OT-000-', RIGHT(YEAR(GETDATE()), 2));
SET
@aux2 = SUBSTRING(
@aux, CHARINDEX('-', @aux) + 1,
LEN(@aux) - CHARINDEX('-', @aux) - CHARINDEX('-', REVERSE(@aux)));
SET @aux3 = CAST(@aux2 AS int) + 1;
SET @aux4 = @aux3;
IF @aux3 < 1000
IF @aux3 >= 10
SET @aux4 = CONCAT('0', @aux4);
ELSE
SET @aux4 = CONCAT('00', @aux4);
ELSE
SET @aux4 = @aux4;
DECLARE @f varchar(100);
DECLARE @y varchar(50);
SELECT TOP 1
@y = id_workorder
FROM workorder
WHERE (RIGHT(id_workorder, 2)) = (RIGHT(YEAR(GETDATE()), 2))
ORDER BY id_workorder DESC;
DECLARE @yy varchar(10);
SET
@yy = RIGHT(@y, 2);
DECLARE @yn varchar(10);
SET
@yn = RIGHT(YEAR(GETDATE()), 2);
BEGIN
IF @yn = @yy
BEGIN
DECLARE @laux varchar(20)
SET @f = 'OT-' + @aux4 + '-' + RIGHT(YEAR(GETDATE()), 2);
INSERT INTO workorder (id_workorder, name, area, initial_date, end_date)
VALUES (@f, @name, @area, @idate, @edate);
SELECT
@laux = id_workorder
FROM idaux
IF (@laux IS NULL)
BEGIN
INSERT idaux (id_workorder) VALUES (@f);
END
ELSE
BEGIN
UPDATE idaux SET id_workorder = @f;
END
END
ELSE
BEGIN
SET @f = CONCAT('OT-001-', (RIGHT(YEAR(GETDATE()), 2)));
INSERT INTO workorder (id_workorder, name, area, initial_date, end_date)
VALUES (@f, @name, @area, @idate, @edate);
SELECT @laux = id_workorder FROM idaux;
IF (@laux IS NULL)
BEGIN
INSERT idaux (id_workorder) VALUES (@f);
END
ELSE
BEGIN
UPDATE idaux SET id_workorder = @f;
END
END
END
END
Basically, i created an auxiliar table to save the last Work Order ID, then from this table called idaux
i take the ID and i compared to new possible ID by a string handling. Then if the year of the last ID saved are equal to the current year the counter increases, but if not the counter is restarted to 001, the new ID is updated in the auxiliar table and the Work Order is inserted to the table workorder
.
My stored procedure works, but i need your help to optimize the stored procedure. Any question post on comments.