newid

Description

Generates human-readable, globally unique IDs (GUIDs) in two different formats, based on arguments you provide. The length of the human-readable format of the GUID value is either 32 bytes (with no dashes) or 36 bytes (with dashes).

Syntax

newid([optionflag])

Parameters

option flag
  • 0, or no value – the GUID generated is human-readable (varchar), but does not include dashes. This argument, which is the default, is useful for converting values into varbinary.

  • -1 – the GUID generated is human-readable (varchar) and includes dashes.

  • -0x0 – returns the GUID as a varbinary.

  • Any other value for newid returns NULL.

Examples

Example 1

Creates a table with varchar columns 32 bytes long, then uses newid with no arguments with the insert statement:

create table t (UUID varchar(32))
go
insert into t values (newid())
insert into t values (newid())
go
select * from t
UUID
--------------------------------
f81d4fae7dec11d0a76500a0c91e6bf6 
7cd5b7769df75cefe040800208254639

Example 2

Produces a GUID that includes dashes:

select newid(1)
------------------------------------
b59462af-a55b-469d-a79f-1d6c3c1e19e3

Example 3

Creates a default that converts the GUID format without dashes to a varbinary(16) column:

create table t (UUID_VC varchar(32), UUID varbinary(16))
go
create default default_guid
as
strtobin(newid())
go
sp_bindefault default_guid, "t.UUID"
go
insert t (UUID_VC) values (newid())
go

Example 4

Returns a new GUID of type varbinary for every row that is returned from the query:

select newid(0x0) from sysobjects

Example 5

Uses newid with the varbinary datatype:

sp_addtype binguid, "varbinary(16)"
create default binguid_dflt
as 
newid(0x0)
sp_bindefault "binguid_dflt","binguid"
create table T1 (empname char(60), empid int, emp_guid binguid)
insert T1 (empname, empid) values ("John Doe", 1)
insert T1 (empname, empid( values ("Jane Doe", 2)

Usage

Standards

ANSI SQL – Compliance level: Transact-SQL extension.

Permissions

Any user can execute newid.