Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: IIS4,IIS5,SS7,SS2K
Expertise: Intermediate
Feb 8, 2001



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Create a GUID from ASP using SQL Server

At times you may need to create a GUID from ASP, for example when assigning unique IDs to users that are visiting your site for the first time. While you can generate new GUIDs from VB quite easily with a call to the CoCreateGUID API call (as explained elsewhere in the Tip Bank, see below), you can't do the same from ASP because you can't call any Windows API from VBScript.

If you have a SQL Server installed on your network, however, you can easily create a new GUID by calling the T-SQL function named NEWID(). Here's a VBScript routine that creates a new GUID and returns it to the caller:

Function CreateGUID()
    Dim cn
    Dim rs 

    Set cn = Server.CreateObject("ADODB.Connection")
    ' adjust the connection string if required
    cn.Open "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Data " _
        & "Source=(local)"
    Set rs = cn.Execute("SELECT NEWID()")
    If Not rs.EOF Then CreateGUID = rs(0)

    ' clean up 
End Function 
Note that the connection string doesn't need to point to a specific database, and that the query string passed as an argument to the Connection's Execute method doesn't have to refer to a specific table. Of course, if you already have a connection open, you can skip the statements that create and open the Connection object.
Francesco Balena
Thanks for your registration, follow us on our social networks to keep up-to-date