加入2个表,一个GUID带破折号,一个不带破折号

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

我正在尝试连接多个表-问题是其中一个表中的GUID没有破折号。

到目前为止,我在研究中发现的是通过这种方式转换单个GUID:

DECLARE @uuid VARCHAR(50)

SET @uuid = 'ecd5bc3f5cf741acabbbf0fb17634970'

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 tsql guid
1个回答
0
投票

进行连接的一种方法是转换为字符串:

select . . .
from t t1 join
     t t2
     on t1.uuid = replace(convert(varchar(36), t2.uuid), '-', '')

我应该注意,这使优化变得困难。您可能需要修改第一个表,使其具有正确类型的uuid列:

alter table t1 add uuid_correct as
    (convert(uniqueidentifier,
             substring(@uuid, 1, 8) + '-' + substring(@uuid, 9, 4) + '-' + substring(@uuid, 13, 4) + '-' +
             substring(@uuid, 17, 4) + '-' + substring(@uuid, 21, 12)
            )
    );

您可以保留该列并在其上建立索引。

© www.soinside.com 2019 - 2024. All rights reserved.