在 SQL Server 中将 varchar 转换为 uniqueidentifier [英] Convert varchar to uniqueidentifier in SQL Server

查看:73
本文介绍了在 SQL Server 中将 varchar 转换为 uniqueidentifier的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

我想将这些转换为 SQL 中的 uniqueidentifiers 以传递给 .Net Guid.但是,以下查询行对我不起作用:

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')

并导致:

Msg 8169, Level 16, State 2, Line 1
Conversion failed when converting from a character string to uniqueidentifier.

使用带连字符的 uniqueidentifier 的相同查询工作正常,但数据未以该格式存储.

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

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

Is there another (efficient) way to convert these strings to uniqueidentifiers in SQL. -- I don't want to do it in the .Net 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)

这篇关于在 SQL Server 中将 varchar 转换为 uniqueidentifier的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆