15

I want to automatically generate unique id with per-defined code attach to it.

ex:

UID12345678
CUSID5000

I tried uniqueidentifier data type but it generate a id which is not suitable for a user id.

Any one have suggestions?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Nishantha
  • 6,065
  • 6
  • 33
  • 51

6 Answers6

36

The only viable solution in my opinion is to use

  • an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
  • a computed, persisted column to convert that numeric value to the value you need

So try this:

CREATE TABLE dbo.tblUsers
  (ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
   UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
   .... your other columns here....
  )

Now, every time you insert a row into tblUsers without specifying values for ID or UserID:

INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)

then SQL Server will automatically and safely increase your ID value, and UserID will contain values like UID00000001, UID00000002,...... and so on - automatically, safely, reliably, no duplicates.

Update: the column UserID is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • first id has to be bigint.second how will 12345678 geenerated with your table like this UID0000000012345678 . so it has to be UDF and format 0000... using replicate . – KumarHarsh Dec 19 '13 at 06:04
  • 1
    thax @marc_s, work without errors. :) Another small issue can 00000000 generate randomly without incrementing?? – Nishantha Dec 19 '13 at 06:09
  • @KumarHarsh - What do you think `UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED` does? – Raj Dec 19 '13 at 06:28
  • marc_s I have a problem. I can't create a foreign key in another table which is referring to UID column of User table because UID doesn't have a data type. How to overcome this? – Elham Kohestani Apr 08 '17 at 15:45
  • @ElhamKohestani: see my update, ***OF COURSE*** it has a datatype !! – marc_s Apr 08 '17 at 16:14
  • Thank you, got it. But I still have a problem since it is nullable I can't refer it to a foreign key. I tried to modify it but it says Property can not be modified. How can I modify it to prevent from null values? – Elham Kohestani Apr 08 '17 at 16:24
  • What if I add 'not null' at the end of column during the table creation query ? – Elham Kohestani Apr 08 '17 at 16:27
  • I tried to alter it but it says: Cannot alter column 'UID' because it is 'COMPUTED'. – Elham Kohestani Apr 08 '17 at 16:33
  • @ElhamKohestani: you need to define it like this, if it has to be not nullable: `UserID AS ISNULL('UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8), '*') PERSISTED` - with the use of `ISNULL()`, you can make sure that it's never ever going to be null – marc_s Apr 08 '17 at 17:16
  • @marc_s thank you. I already solved that by creating the table from scratch and adding a UNIQUE constraint on the column. Won't it cause any problem in the future? – Elham Kohestani Apr 08 '17 at 17:43
  • @ElhamKohestani: no, since the `ID` is an identity, that in itself is unique, so any computed column based on that value will be unique, too – marc_s Apr 08 '17 at 18:07
  • Thank you @marc_s could you answer my question, please? http://stackoverflow.com/questions/43298886/how-to-calculate-the-custom-id-for-a-row-which-has-not-been-inserted-yet – Elham Kohestani Apr 08 '17 at 18:34
4
CREATE TABLE dbo.tblUsers
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED, 
    [Name] VARCHAR(50) NOT NULL,
)

marc_s's Answer Snap

marc_s's Answer Snap

Community
  • 1
  • 1
Nishantha
  • 6,065
  • 6
  • 33
  • 51
  • I have not tried something like that in mysql. But you can ask it from the genius @marc_s – Nishantha Apr 19 '16 at 05:33
  • 1
    @MohammedHousseynTaleb: sorry, I don't know MySQL well enough to tell you whether it supports this kind of thing.... but **YOU** can consult the **MySQL documentation** and see if it does! – marc_s Apr 19 '16 at 06:34
2

Reference:https://learn.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-2017

-- Creating a table using NEWID for uniqueidentifier data type.

CREATE TABLE cust  
(  
 CustomerID uniqueidentifier NOT NULL  
   DEFAULT newid(),  
 Company varchar(30) NOT NULL,  
 ContactName varchar(60) NOT NULL,   
 Address varchar(30) NOT NULL,   
 City varchar(30) NOT NULL,  
 StateProvince varchar(10) NULL,  
 PostalCode varchar(10) NOT NULL,   
 CountryRegion varchar(20) NOT NULL,   
 Telephone varchar(15) NOT NULL,  
 Fax varchar(15) NULL  
);  
GO  
-- Inserting 5 rows into cust table.  
INSERT cust  
(CustomerID, Company, ContactName, Address, City, StateProvince,   
 PostalCode, CountryRegion, Telephone, Fax)  
VALUES  
 (NEWID(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,  
 '90110', 'Finland', '981-443655', '981-443655')  
,(NEWID(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',  
 '08737-363', 'Brasil', '(14) 555-8122', '')  
,(NEWID(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,   
 '1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')  
,(NEWID(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,  
 '8010', 'Austria', '7675-3425', '7675-3426')  
,(NEWID(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,  
 'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68');  
GO
Amin Golmahalleh
  • 3,585
  • 2
  • 23
  • 36
Julius Depulla
  • 1,493
  • 1
  • 12
  • 27
1

The 'newid()' method unique id generate for per record.


AddColumn("dbo.Foo", "Key", c => c.String(nullable: false, maxLength: 250, defaultValueSql: "newid()"));

Mico
  • 70
  • 6
0

If you want to add the id manually you can use,

PadLeft() or String.Format() method.

string id;
char x='0';
id=id.PadLeft(6, x);
//Six character string id with left 0s e.g 000012

int id;
id=String.Format("{0:000000}",id);
//Integer length of 6 with the id. e.g 000012

Then you can append this with UID.

Nishantha
  • 6,065
  • 6
  • 33
  • 51
0

Table Creating

create table emp(eno int identity(100001,1),ename varchar(50))

Values inserting

insert into emp(ename)values('narendra'),('ajay'),('anil'),('raju')

Select Table

select * from emp

Output

eno     ename
100001  narendra
100002  rama
100003  ajay
100004  anil
100005  raju
Amin Golmahalleh
  • 3,585
  • 2
  • 23
  • 36