0

I want to create a table in sql server and fill it up with data (people's info) every person should have a unique ID different than the auto incremented ID's by sql server For example i need the ID for the first person inserted like this: 2016xxxx how to fix the 2016 and randomly generate the numbers after that to be filled instead of xxxx should i use a regular expression ?

2 Answers2

0

You could create a function that would get the next value for you and use that instead of an AUTO_INCREMENT field.

I wouldn't recommend it tho. You shouldn't format the data like that before inserting it. That sort of thing should be done on the way out, preferably by the front-end code. Or you can just write a query and create a view ... However if you must do that here is the complete answer with the code: Is there a way to insert an auto-incremental primary id with a prefix in mysql database?

Community
  • 1
  • 1
Iman
  • 647
  • 13
  • 30
0

You can also create a computed column like below

CREATE TABLE tableName
(
    PkAutoId INT PRIMARY KEY IDENTITY(1,1),
    PersonUniqueNo AS (CAST(DATEPART(YEAR,GETDATE()) AS VARCHAR) + RIGHT(RIGHT(CAST(RAND() AS VARCHAR),4) + CAST(PkAutoId AS VARCHAR),4))
)

Computed Column "PersonUniqueNo" is 8 Digit Unique Number comprising of Current Year And Conceited value of Random number and Primary Key Id for 4 Length, Total length will be 8 as asked.

Bhavesh Harsora
  • 479
  • 4
  • 13