jeudi 16 juin 2011
SQL Server: use the NewId() function to create unique identifiers
Do you like this story?
A few months ago, I have published an article mentioning the NewId() SQL function. In that post, I was explaining how to create dynamic keywords and description meta tags. However the NewId() function can be used in different situations and it becomes very handy, when we need unique identifiers.
Let's see how it works.
The basics
The NewId() function returns a unique identifier; that means a unique set of numbers and letters. If we use the function in a query in SQL Server Management Studio like:print newid()5C6C9372-49F9-4A5C-BCFA-DA6CDB525CABGlobally Unique Identifier
If we need to create PINs, passwords, or in general, unique identifiers, we can use the NewId() function directly in our tables. To do so, we can set the default value of a field as NewId(). When we insert a new record in that table, we do not need to think about the unique identifier, because it will be inserted automatically and it will be globally unique. The only inconvenience might be the fact that the generated unique identifier could be too long. In those case, I have some times used as column default value something like:(left(newid(),(4)))Replace(newid(),'-','')Order a table randomly
We can use the NewId() function to randomly order a table:select * 
from table
order by newid()select top(1) *
from table
order by newid()New ideas?
Well, in my experience the NewId() function can be used in different and creative way. I have used it for automatic login password generators and for PINs in a company project protection forms. But whenever I need to create a GUI, I always use it, even when the GUI is not actually saved in a table.Have a splendid day and let me know what you think about it.

This post was written by: Franklin Manuel
Franklin Manuel is a professional blogger, web designer and front end web developer. Follow him on Twitter
Inscription à :
Publier les commentaires (Atom)


0 Responses to “SQL Server: use the NewId() function to create unique identifiers”
Enregistrer un commentaire