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
  • 25,246
  • 15
  • 42
  • 71
bmurf17
  • 83
  • 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,393
  • 2
  • 11
  • 23
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
  • 27,362
  • 33
  • 117
  • 216
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
  • 6,090
  • 1
  • 15
  • 42