NewGuid() ("M" Reference)

[This content is no longer valid. For the latest information on "M", "Quadrant", SQL Server Modeling Services, and the Repository, see the Model Citizen blog.]

This function is used to guarantee a globally-unique identifier, or GUID, value for the primary key of the generated table.

Example

The following example uses the NewGuid() function to create a Guid field as the identity.

module Northwind {
    type Employee
    {
        Id : Guid = NewGuid();
    } where identity(Id);
    Employees : Employee;
}

The preceding code generates the following T-SQL code when compiled. The T-SQL uniqueidentifier data type represents a 16-bit GUID. The instead of trigger uses the coalesce function to handle the case where an attempt is made to insert a row with a null primary key.

create table [Northwind].[Employees]
(
  [Id] uniqueidentifier not null,
  constraint [PK_Employees] primary key clustered ([Id])
);
go

create trigger [Northwind].[Employees_insert_trigger]
  on [Northwind].[Employees]
  instead of insert
  as
  begin
    insert into [Northwind].[Employees] ([Id])
    select (coalesce([t0].[Id], newid()))
    from inserted as [t0];
  end
go