How to create a list of increasing unique identifiers?
0
votes
0
answers
395
views
I'm creating a list of Connections objects (names of machines with IP address and IP port), but I'm having an issue with the
Id
field.
Normally this is the way I would work:
INSERT INTO [CONNECTIONS] ([Id], [Name], [Address]) VALUES (1, 'Connection_1', '1.1.1.1')
INSERT INTO [CONNECTIONS] ([Id], [Name], [Address]) VALUES (2, 'Connection_2', '2.2.2.2')
...
... but as my Id
field is not a simple int
, but a uniqueidentifier
this doesn't work.
So, I tried with NEWID()
:
INSERT INTO [CONNECTIONS] ([Id], [Name], [Address]) VALUES (NEWID(), 'Connection_1', '1.1.1.1')
INSERT INTO [CONNECTIONS] ([Id], [Name], [Address]) VALUES (NEWID(), 'Connection_2', '2.2.2.2')
...
That worked, but the newly generated IDs were created randomly, so when asking the result, I did not get "Connection_1" up to "Connection_10", but something like "Connection_3", then "Connection_8", only then "Connection_1", ..., quite messy.
So I tried again, this time using NEWSEQUENTIALID()
, so I had following SQL "INSERT INTO" queries:
INSERT INTO [CONNECTIONS] ([Id], [Name], [Address]) VALUES (NEWSEQUENTIALID(), 'Connection_1', '1.1.1.1')
INSERT INTO [CONNECTIONS] ([Id], [Name], [Address]) VALUES (NEWSEQUENTIALID(), 'Connection_2', '2.2.2.2')
...
As a result, I got "Commands completed successfully", but my table turns out empty :-(
I don't need my IDs to be sequential, I just want them to be ordered from small to large (as can be expected from an ID, at least that's what I thought).
How can I achieve that? (I'm working with SQL-Server, using SQL Server Management Studio version v18.12).
Asked by Dominique
(609 rep)
Oct 6, 2022, 08:25 AM