2

I need to copy data from one SQL table to another table where I need this conversion, I tried the following:

SELECT TOP 10 CAST(Per_ID as UniqueIdentifier FROM Test

SELECT TOP 10 CONVERT(UniqueIdentifier,Per_ID,100) FROM Test

Both giving me this error:

Conversion failed when converting from a character string to uniqueidentifier.

Sergey
  • 1,608
  • 1
  • 27
  • 40
Arvinder Rehal
  • 31
  • 1
  • 1
  • 2

3 Answers3

1

You can create a user defined function for this conversion (assuming MS SQL Server is being used):

IF OBJECT_ID (N'dbo.NvarcharToUniqueidentifier', N'FN') IS NOT NULL
    DROP FUNCTION dbo.NvarcharToUniqueidentifier;
GO
CREATE FUNCTION dbo.NvarcharToUniqueidentifier (@id nvarchar(100))
RETURNS UNIQUEIDENTIFIER
WITH EXECUTE AS CALLER
AS
BEGIN
RETURN CAST(LEFT(@id, 8)
            + '-' +RIGHT(LEFT(@id, 12), 4)
            + '-' +RIGHT(LEFT(@id, 16), 4)
            + '-' +RIGHT(LEFT(@id, 20), 4)
            + '-' +RIGHT(@id, 12) 
            AS UNIQUEIDENTIFIER);
END
GO

And you can call this function as below:

select dbo.NvarcharToUniqueidentifier('1915DE0055FA11D6A6E40008C7D0BAB1')

The output is: 1915DE00-55FA-11D6-A6E4-0008C7D0BAB1

skjcyber
  • 5,759
  • 12
  • 40
  • 60
0

Uniqueindentifier can only contain HEX values, it means A-F and 0-9.

Senaid
  • 1
0

you can use this script to convert varchar to GUID

DECLARE @uuid VARCHAR(50)
SET @uuid = '1915DE0055FA11D6A6E40008C7D0BAB1'
SELECT  CAST(
        SUBSTRING(@uuid, 1, 8) + '-' + SUBSTRING(@uuid, 9, 4) + '-' + SUBSTRING(@uuid, 13, 4) + '-' +
        SUBSTRING(@uuid, 17, 4) + '-' + SUBSTRING(@uuid, 21, 12)
        AS UNIQUEIDENTIFIER)
VahiD
  • 1,014
  • 1
  • 14
  • 30