Convert varchar to uniqueidentifier in SQL Server

一个我不能控制模式的表包含一个定义为 varchar (50)的列,该列以‘ a89b1acd95016ae6b9c8aabb07da2010’(无连字符)的格式存储惟一标识符

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.

使用带有连字符的唯一标识符的相同查询可以正常工作,但数据不以该格式存储。

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

313210 次浏览
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)

your varchar col C:

SELECT CONVERT(uniqueidentifier,LEFT(C, 8)
+ '-' +RIGHT(LEFT(C, 12), 4)
+ '-' +RIGHT(LEFT(C, 16), 4)
+ '-' +RIGHT(LEFT(C, 20), 4)
+ '-' +RIGHT(C, 12))

这将会是一个很方便的函数。同时,注意我使用的是 STUFF 而不是 SUBSTRING。

create function str2uniq(@s varchar(50)) returns uniqueidentifier as begin
-- just in case it came in with 0x prefix or dashes...
set @s = replace(replace(@s,'0x',''),'-','')
-- inject dashes in the right places
set @s = stuff(stuff(stuff(stuff(@s,21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-')
return cast(@s as uniqueidentifier)
end

或者一句俏皮话:

cast(stuff(stuff(stuff(stuff(replace(replace(@s,'0x',''),'-',''),21,0,'-'),17,0,'-'),13,0,'-'),9,0,'-') as uniqueidentifier)

提供的指南格式不正确(. net 提供的指南)。

begin try
select convert(uniqueidentifier,'a89b1acd95016ae6b9c8aabb07da2010')
end try
begin catch
print '1'
end catch
SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('B33D42A3AC5A4D4C81DD72F3D5C49025',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))
SELECT CAST(CAST('A89B1ACD-9501-6AE6-B9C8-AABB07DA2010' as char(36)) as uniqueidentifier)