Click here to Skip to main content
15,917,971 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to get a unique number in sql.
Format is as below:
DDMMYYXXXX
where DDMMYY (Current Date in DDMMYY Format) and
XXXX a 4 digit recurring number

What I have tried:

select @test=REPLACE(CONVERT(CHAR(10), GETDATE() , 103), '/', '')
Posted
Updated 23-Aug-16 8:58am
v2

1 solution

Check this: sql server - How to autoincrement a varchar - Stack Overflow[^]

[EDIT]
A table definition should look like (replace YourTableName with the name you want to use):
SQL
CREATE TABLE YourTableName
(
    ID INT IDENTITY(1,1),
    CurrDate DATE,
    CID INT,
    VCID VARCHAR(10)
)


Let's insert sample data:
SQL
--insert sample data
INSERT INTO YourTableName(CurrDate, CID, VCID)
VALUES('2016-08-23', 5, '2308160005'),
('2016-08-23', 6, '2308160006'),
('2016-08-23', 7, '2308160007')


Then you have to create stored procedure[^]

SQL
CREATE STORED PROCEDURE cspInsertMyData
AS
BEGIN
    --declare variables
    DECLARE @d DATE = GETDATE()
    --max of CID
    DECLARE @nextcid INT = 0
    --initiate variable
    SELECT @nextcid = COALESCE(MAX(CID), 0) + 1 FROM YourTableName

    INSERT INTO YourTableName (CurrDate, CID, VCID)
    VALUES(@d, @nextcid, FORMAT(@d, 'ddMMyy') + RIGHT('0000' + CONVERT(VARCHAR(4), @nextcid), 4))

END;


A result:
C#
ID	CurrDate	CID	VCID
1	2016-08-23	5	2308160005
2	2016-08-23	6	2308160006
3	2016-08-23	7	2308160007
4	2016-08-23	8	2308160008



[/EDIT]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900