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.
            Asked
            
        
        
            Active
            
        
            Viewed 90 times
        
    1
            
            
        - 
                    3And why not use `identity`? – Gordon Linoff Oct 20 '19 at 19:45
 
3 Answers
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