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 rs.Close cn.Close 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.