How to Convert varchar to uniqueidentifier in SQL Server

By FoxLearn 2/13/2025 1:59:29 AM   1.77K
To convert a varchar to a uniqueidentifier in SQL Server, you can use the CAST or CONVERT function.

In SQL Server, you can generate a new GUID (or uniqueidentifier) using the NEWID() function.

SELECT NEWID() AS NewGUID;

This will return a newly generated GUID like:

A6F6C0A4-5B69-4C3C-AF6A-39D1B2557123

Every time you call NEWID(), it generates a unique GUID.

How to convert sql string to uniqueidentifier?

Converting VARCHAR to UNIQUEIDENTIFIER in SQL Server involves using the CAST or CONVERT functions. However, since UNIQUEIDENTIFIER is a specific data type that represents a globally unique identifier (GUID), you need to ensure that the values in your VARCHAR are in a format that can be converted to a UNIQUEIDENTIFIER.

For example, sql convert string to guid:

id: a79b1ecd95015ae6b9c8aabb07da1020 // sql string to guid

To convert sql string to uniqueidentifier you can use the sql query as shown below.

// to sql string uniqueidentifier
SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('a79b1ecd95015ae6b9c8aabb07da1020',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))

Result: sql convert string to uniqueidentifier

A79B1ECD-9501-5AE6-B9C8-AABB07DA1020

If you have a varchar value representing a GUID, like '550e7400-e29b-41d4-a716-446655440000', you would do.

// convert string to uniqueidentifier sql
SELECT CAST('550e7400-e29b-41d4-a716-446655440000' AS uniqueidentifier)

Ensure that the varchar value is in the correct GUID format; otherwise, the conversion will fail. If you attempt to convert a varchar that is not a valid GUID, you will encounter an error.

To avoid errors with invalid formats, you can use a TRY_CAST or TRY_CONVERT, which will return NULL for invalid conversions:

SELECT TRY_CAST('invalid guid' AS uniqueidentifier)

Cast uniqueidentifier to varchar sql server

In SQL Server, you can cast a uniqueidentifier to a varchar using the CAST or CONVERT function.

For example, using CAST:

SELECT CAST(your_column AS VARCHAR(36)) 
FROM your_table

// example convert guid to varchar in sql
SELECT CAST('7EA52055-BCF2-4AE1-8C91-F4FFF668ECF7' AS VARCHAR(36))

For example, using CONVERT:

SELECT CONVERT(VARCHAR(36), your_column) 
FROM your_table

// example convert guid to varchar in sql
SELECT CONVERT(VARCHAR(36), '7EA52055-BCF2-4AE1-8C91-F4FFF668ECF7')

Both CAST and CONVERT work similarly here, and the output will be a string representation of the GUID value.