Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate unique value in MS SQL

I have primary key unique column ID nchar(10). I'm planning to generate in it numeric ID. Incremental order is ok, but not necessary. How to make optimal generator for this reason? Should I use stored procedure? Maybe MS SQL server have any features for this reason?

like image 503
vico Avatar asked Dec 07 '25 22:12

vico


1 Answers

DECLARE PkStudentid as INT

CREATE TABLE Student 
(
 Studentid int IDENTITY (1, 1) NOT NULL PRIMARY KEY,
 Firstname nvarchar (200) NULL,
 Lastname nvarchar (200),
 Email nvarchar (100) NULL
)

insert into Student (Firstname,Lastname,Email)
Values('Vivek', 'Johari', ‘[email protected]');

SET @PkStudentid  = SCOPE_IDENTITY();

print @PkStudentid

This will insert Studentid as 1 and next entry 2 and in increment order.

You need to use IDENTITY property in SQL Server.

Edited : use SCOPE_IDENTITY in SQL Server to get back latest inserted Studentid.

like image 165
Vishwanath Dalvi Avatar answered Dec 09 '25 14:12

Vishwanath Dalvi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!