How to convert varchar to uniqueidentifier in SQL Server

By FoxLearn 11/21/2024 1:53:31 AM   433
To convert a varchar to a uniqueidentifier in SQL Server, you can use the CAST or CONVERT function.

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.

How to convert sql string to uniqueidentifier?

For example sql convert string to guid:

id: a79b1ecd95015ae6b9c8aabb07da1020

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

SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('a79b1ecd95015ae6b9c8aabb07da1020',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))

Result

A79B1ECD-9501-5AE6-B9C8-AABB07DA1020

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

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)