Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

A table I have no control of the schema for, contains a column defined as varchar(50) which stores uniqueidentifiers in the format 'a89b1acd95016ae6b9c8aabb07da2010' (no hyphens)

I want to convert these to uniqueidentifiers in SQL for passing to a .Net Guid. However, the following query lines don't work for me:

select cast('a89b1acd95016ae6b9c8aabb07da2010' as uniqueidentifier)

select convert(uniqueidentifier, 'a89b1acd95016ae6b9c8aabb07da2010')

and result in:

Msg 8169, Level 16, State 2, Line 1

Conversion failed when converting from a character string to uniqueidentifier.

The same queries using a hyphenated uniqueidentifier work fine but the data is not stored in that format.

Is there another (efficient) way to convert these strings to uniqueidentifiers in SQL. -- I don't want to do it in the .Net code.

3 Answers

0 votes
by (40.7k points)

Try using the below code:

DECLARE @uuid VARCHAR(50)

SET @uuid = 'a89b1acd95016ae6b9c8aabb07da2010'

SELECT  CAST(

        SUBSTRING(@uuid, 1, 8) + '-' + SUBSTRING(@uuid, 9, 4) + '-' + SUBSTRING(@uuid, 13, 4) + '-' +

        SUBSTRING(@uuid, 17, 4) + '-' + SUBSTRING(@uuid, 21, 12)

        AS UNIQUEIDENTIFIER)

If you wish to learn SQL then visit this SQL Training.

0 votes
by (37.3k points)

To convert Varchar  string without hyphens to a uniqueidentifier in SQL server  :

    DECLARE @uuid VARCHAR(50)

   SET @uuid = 'a89b1acd95016ae6b9c8aabb07da2010' 

   SELECT CAST(

   SUBSTRING(@uuid, 1, 8) + '-' + SUBSTRING(@uuid, 9, 4) + '-' + SUBSTRING(@uuid, 13, 4) + '-' +                SUBSTRING(@uuid, 17, 4) + '-' + SUBSTRING(@uuid, 21, 12) 

  AS UNIQUEIDENTIFIER)

This SQL command is useful for enlarging the volume of text columns to handle huge or more complex text data

0 votes
ago by (3.1k points)

If you want to convert the Varchar string without using any hyphen in SQL server. You can refer to the below code:

DECLARE @uuid VARCHAR(50)

SET @uuid = 'a89b1acd95016ae6b9c8aabb07da2010'

SELECT CAST(

    SUBSTRING(@uuid, 1, 8) + '-' + 

    SUBSTRING(@uuid, 9, 4) + '-' + 

    SUBSTRING(@uuid, 13, 4) + '-' + 

    SUBSTRING(@uuid, 17, 4) + '-' + 

    SUBSTRING(@uuid, 21, 12) 

AS UNIQUEIDENTIFIER)

It will help you in formatting a string as a unique identifier

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...