Pagina's

donderdag 1 februari 2018

T-SQL:Unique identifier as a primary key with auto generated key

Several days ago I created a table with an unique identifier as a primary key with a default value. I thought this might be interesting for other developers :) #SharingIsCaring

I like to have an auto generated  default value for this primary key.
You can't use the Identity(1,1) property on an unique identifier, this will generate an error.





The solution for this is the NewId() function. 
Here is an example:
create table Product(
 Id uniqueidentifier primary key default newid(), 
 ProductName nvarchar(255), 
 Price float,
 IsInStock bit default 0,
)


You can now insert a record in the table.
insert into Product (ProductName,Price) Values('Iphone X',999.99)


 Do a select all from the product table ,you wil see the record that you've created.

select * from Product
Notice the auto generated value for the id column.



That's want we want !