locked
Most efficient way to convert strings to uniqueidentifier RRS feed

  • Question

  • Hello,

    I have semi-guid strings in a format like 'aa0d586c8a495c9400de3796fa8e0cbd' all over my database columns.

    What would be the most efficient way to convert such string to uniqueidentifier?

    Thank you


    Wednesday, June 8, 2016 12:22 AM

Answers

  • You only have to add some minus sign, then you can convert it:

    DECLARE @string varchar(40) = 'aa0d586c8a495c9400de3796fa8e0cbdef0';
    
    SELECT CONVERT(uniqueidentifier,
                   SUBSTRING(@string, 1, 8) + '-' + 
                   SUBSTRING(@string, 9, 4) + '-' + 
                   SUBSTRING(@string, 14, 4) + '-' + 
                   SUBSTRING(@string, 19, 4) + '-' + 
                   SUBSTRING(@string, 24, 12)) AS MyGUID


    Olaf Helper

    [ Blog] [ Xing] [ MVP]

    Wednesday, June 8, 2016 7:47 AM

All replies

  • You only have to add some minus sign, then you can convert it:

    DECLARE @string varchar(40) = 'aa0d586c8a495c9400de3796fa8e0cbdef0';
    
    SELECT CONVERT(uniqueidentifier,
                   SUBSTRING(@string, 1, 8) + '-' + 
                   SUBSTRING(@string, 9, 4) + '-' + 
                   SUBSTRING(@string, 14, 4) + '-' + 
                   SUBSTRING(@string, 19, 4) + '-' + 
                   SUBSTRING(@string, 24, 12)) AS MyGUID


    Olaf Helper

    [ Blog] [ Xing] [ MVP]

    Wednesday, June 8, 2016 7:47 AM
  • Thanks Uri. I was hoping there might be a shorter way of doing this.
    Wednesday, June 8, 2016 4:59 PM