Introduction
As we all know, SQL provides functionality for auto incremented columns and we (mostly) use them for creating primary keys. But there is a limitation for it, it will auto increment only NUMERIC values like 1, 2, 3……up to N. But sometimes, we need something like this. Suppose I have a table which will hold data from many departments like Marketing, HR, Networking, etc., and my requirement is something like to insert a PK like M001, M002, M003…. if Marketing Department Record, and N001, N002, N003…. If Networking Department record or same as for HR likes H001, H002, H003... So how to manage this automatically.
The logic for creating auto incremented ID with VARCHAR
/NVARCHAR
data type is modified as per the requirement.
Solution
CREATE TABLE TESTING(
ID VARCHAR(5),
NAME VARCHAR(15),
DESCP VARCHAR(50)
);
GO
CREATE PROCEDURE SP_INSERT
@NAME VARCHAR(MAX),
@DESCP VARCHAR(MAX)
AS
BEGIN
DECLARE @NEWID VARCHAR(5);
DECLARE @PREFIX VARCHAR(1);
SET @PREFIX = UPPER(SUBSTRING(@NAME, 1, 1))
SELECT @NEWID = (@PREFIX + replicate('0', 3 - len(CONVERT(VARCHAR,N.OID + 1))) + _
CONVERT(VARCHAR,N.OID + 1)) FROM (
SELECT CASE WHEN MAX(T.TID) IS null then 0 else MAX(T.TID) end as OID FROM (
SELECT SUBSTRING(ID, 1, 1) as PRE_FIX,SUBSTRING(ID, 2, LEN(ID)) as TID FROM Testing
) AS T WHERE T.PRE_FIX = @PREFIX
) AS N
INSERT INTO Testing VALUES (@NEWID,@NAME,@DESCP)
END
GO
SP_INSERT 'MANAGEMENT','YOUR MANAGEMENT DESCRIPTION';
SP_INSERT 'NETWORK','YOUR NETWORK DESCRIPTION';
SP_INSERT 'HR','YOUR HR DESCRIPTION';
SP_INSERT 'MANAGEMENT','YOUR MANAGEMENT DESCRIPTION 2';
SP_INSERT 'NETWORK','YOUR NETWORK DESCRIPTION 2';
SP_INSERT 'HR','YOUR HR DESCRIPTION 2';
SELECT * FROM TESTING
Result
ID NAME DESCP
----- --------------- ------------------------------
M001 MANAGEMENT YOUR MANAGEMENT DESCRIPTION
N001 NETWORK YOUR NETWORK DESCRIPTION
H001 HR YOUR HR DESCRIPTION
M002 MANAGEMENT YOUR MANAGEMENT DESCRIPTION 2
N002 NETWORK YOUR NETWORK DESCRIPTION 2
H002 HR YOUR HR DESCRIPTION 2