Create unique value in MS SQL

I have a unique nchar (10) column id. I am planning on generating a numeric id in it. Incremental order is fine, but not needed. How to make an optimal generator for this reason? Should I be using a stored procedure? Maybe MS SQL Server has some functionality for this reason?

+3


source to share


3 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', โ€˜vivekjohari@abc.com');

SET @PkStudentid  = SCOPE_IDENTITY();

print @PkStudentid

      

This will add Studentid as 1 and next entry 2 and in ascending order.



You need to use the IDENTITY property in SQL Server.

Edited: Use SCOPE_IDENTITY in SQL Server to return the last inserted Studentid.

+1


source


For primary key column, you need to use INT column with IDENTITY insert.

Alternative solution:

However, if you do not want to use the INT datatype, an alternative solution is the create column with a default LEFT(NEWID(), 10)

UNIQUE / PRIMARY KEY. Since the function NEWID()

generates different random strings every time.

Example:

SELECT LEFT(REPLACE(NEWID(),'-',''),(10))

      



The above query will give a different random string.

Check SQL FIDDLE DEMO :

OUTPUT

|         ID | NAME |
|------------|------|
| 482E5D4850 |  pqr |
| 70369ED157 |  abc |
| 768CC98442 |  xyz |

      

+1


source


ID int IDENTITY (1, 1) NOT NULL PRIMARY KEY 

      

Use MS SQL IDENTITY property together with PRIMARY KEY for uniqueness.

Columns

Identity

can be used to generate key values. The identity property on a column guarantees the following:

  • Each new value is generated based on the current seed and increment.
  • Each new value for a particular transaction is different from other concurrent transactions in the table.
  • (1,1) - Initial number and Increment value, which you can get at will.
0


source







All Articles