~/docs
Resonate
Resonate
4.x 4.0.0, current 3.x 3.0.1 2.x 2.0.1 1.x 1.3.0
UUID Library
Toggle sidebar
UUID Library
webpatser/uuid 4.0.0

UUID Library 4.x

Microsoft SQL Server

Convert UUIDs to and from the mixed-endian GUID format of SQL Server with importFromSqlServer(), toSqlServer() and toSqlServerBinary().

SQL Server stores a uniqueidentifier with mixed endianness. The first three groups (4, 2 and 2 bytes) are little-endian, the last 8 bytes are big-endian. The same 16 bytes therefore print differently in SQL Server than in an RFC 4122 string.

The library converts between the two with three methods.

Import from SQL Server

use Webpatser\Uuid\Uuid;
 
$uuid = Uuid::importFromSqlServer('825B076B-44EC-E511-80DC-00155D0ABC54');
 
echo $uuid->string; // 6b075b82-ec44-11e5-80dc-00155d0abc54

importFromSqlServer() strips everything that is not a hex digit, so braces and hyphens are fine. It throws an Exception (Invalid SQL Server GUID format.) unless 32 hex digits remain.

Export to SQL Server

$uuid = Uuid::import('6b075b82-ec44-11e5-80dc-00155d0abc54');
 
$guid = $uuid->toSqlServer(); // "825B076B-44EC-E511-80DC-00155D0ABC54"
$binary = $uuid->toSqlServerBinary(); // 16 bytes in SQL Server byte order
Method Returns
Uuid::importFromSqlServer(string $sqlServerGuid) Uuid with standard byte order
$uuid->toSqlServer() Uppercase GUID string in SQL Server byte order
$uuid->toSqlServerBinary() 16-byte string in SQL Server byte order

Table schema

A table keyed on a UNIQUEIDENTIFIER filled from PHP:

CREATE TABLE products (
id UNIQUEIDENTIFIER PRIMARY KEY,
name NVARCHAR(255) NOT NULL,
price DECIMAL(10,2),
created_at DATETIME2 DEFAULT GETDATE()
);

Bind the binary form in SQL Server byte order when inserting:

$uuid = Uuid::v7();
 
$stmt = $pdo->prepare('INSERT INTO products (id, name, price) VALUES (?, ?, ?)');
$stmt->execute([$uuid->toSqlServerBinary(), 'Widget', 9.99]);

Round trip

$uuid = Uuid::v7();
 
$back = Uuid::importFromSqlServer($uuid->toSqlServer());
 
var_dump(Uuid::compare($uuid->string, $back->string)); // bool(true)

Which method to use

  • Reading a uniqueidentifier that SQL Server returned as a string: importFromSqlServer().
  • Sending a UUID to SQL Server as a string: toSqlServer().
  • Sending a UUID to SQL Server as binary: toSqlServerBinary().
  • Storing the standard form (string or bytes) in a char(36) or binary(16) column: no conversion is needed, but those values do not match what SQL Server prints for a uniqueidentifier.