在 SQL Server 中将 varchar 转换为 uniqueidentifier

问题描述 投票:0回答:7

我无法控制其模式的表,包含定义为 varchar(50) 的列,该列以“a89b1acd95016ae6b9c8aabb07da2010”(无连字符)格式存储唯一标识符

我想将它们转换为 SQL 中的唯一标识符,以便传递给 .Net GUID。但是,以下查询行对我不起作用:

select cast('a89b1acd95016ae6b9c8aabb07da2010' as uniqueidentifier)
select convert(uniqueidentifier, 'a89b1acd95016ae6b9c8aabb07da2010')

并导致:

消息 8169,第 16 级,状态 2,第 1 行
从字符串转换为 uniqueidentifier 时转换失败。

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

是否有另一种(有效)方法将这些字符串转换为 SQL 中的唯一标识符。 -- 我不想在 .Net 代码中这样做。

sql sql-server-2005 uniqueidentifier
7个回答
151
投票
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)

30
投票

这将是一个方便的功能。另外,请注意我使用的是 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)

21
投票

你的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))

17
投票
SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('B33D42A3AC5A4D4C81DD72F3D5C49025',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))

1
投票
SELECT CAST(CAST('A89B1ACD-9501-6AE6-B9C8-AABB07DA2010' as char(36)) as uniqueidentifier)

0
投票

我不知道需要多新的 SQL Server 版本才能执行以下操作,但在当前版本中,您可以执行以下操作...

DECLARE @myid uniqueidentifier ;  
SET @myid = 'A972C577-DFB0-064E-1189-0154C99310DAAC12';

这个例子取自微软的文档: https://learn.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql?view=sql-server-ver16


-7
投票

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

begin try
select convert(uniqueidentifier,'a89b1acd95016ae6b9c8aabb07da2010')
end try
begin catch
print '1'
end catch
© www.soinside.com 2019 - 2024. All rights reserved.