Reputation: 125
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.
Upvotes: 1
Views: 98
Reputation: 6465
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;
Upvotes: 1
Reputation: 28550
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.
Upvotes: 2
Reputation: 1414
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.
Upvotes: 3