1

I am trying to enter a row into one of my databases, but I want to make sure the primary key I give it is unique. My primary key is an int. I have tried using newid(), but that does not give me an int back. If there is a way I can get newid() to return just an int, or if another function that would give me an unique int I would use it.

Dale K
  • 21,987
  • 13
  • 41
  • 69
bmurf17
  • 73
  • 7

3 Answers3

3

You could alter the definition of your column to int IDENTITY(1,1) PRIMARY KEY, then don't specify a value when inserting a row, and the ID will auto-increment.

See https://www.w3schools.com/sql/sql_autoincrement.asp for more info.

LegendofPedro
  • 1,363
  • 2
  • 11
  • 22
2

Be careful with a random primary key, especially if it's the clustered index too. It's likely to cause allot of filesystem IO. Use an auto incrementing identity instead.

BanksySan
  • 25,929
  • 29
  • 105
  • 202
1

One object that gives unique ints are the sequences.

You first need to create a sequence :

CREATE SEQUENCE MyNewID START WITH 1 INCREMENT BY 1;  

And then you can retrieve your new ID calling NEXT VALUE every time :

SET @MyNewID = NEXT VALUE FOR MyNewID;
Marc Guillot
  • 5,744
  • 12
  • 34