从字符串转换为uniqueidentifier时转换失败错误?

时间:2016-05-21 13:24:22

标签: sql-server

我想将nvarchar值传递给uniqueidentifier。

例如:

Declare @test nvarchar(max);
set @test =  '''' + '77494371-30c1-4d2e-8dea-58dbefb325cc' + '''' --+ ',' + '''' + 'cb4229a2-76f8-4d68-aef7-f0bae089b382' + '''';
print @test;

Select * from Table1 where ID in (@test);

我试图通过以上条件。那个时候我面临以下错误:

'77494371-30c1-4d2e-8dea-58dbefb325cc','cb4229a2-76f8-4d68-aef7-f0bae089b382'
Msg 8169, Level 16, State 2, Line 5
Conversion failed when converting from a character string to uniqueidentifier.

如果有任何方法可以将多个uniqueidentifier值传递给Where In条件。

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

目前,您的查询将被解析为

Select * 
from Table1 
where ID in ('''77494371-30c1-4d2e-8dea-58dbefb325cc','cb4229a2-76f8-4d68-aef7-f0bae089b382''')

您的输入'''77494371-30c1-4d2e-8dea-58dbefb325cc','cb4229a2-76f8-4d68-aef7-f0bae089b382'''绝对不是Unique Identifier,因此您会收到该错误

我建议你采用以下方法

Declare @guid_col table(guid_col uniqueidentifier);

insert into @guid_col 
values('77494371-30c1-4d2e-8dea-58dbefb325cc'),
       ('cb4229a2-76f8-4d68-aef7-f0bae089b382')

Select * from Table1 where ID in(select guid_col from @guid_col)

或者你需要一个拆分字符串函数,你需要在@test变量中拆分逗号分隔值并在Where子句中使用它。有关拆分字符串功能的信息,请查看以下链接

Split strings the right way – or the next best way

答案 1 :(得分:1)

试试这个......

Declare @test nvarchar(max), @xml XML;
set @test =  '77494371-30c1-4d2e-8dea-58dbefb325cc,cb4229a2-76f8-4d68-aef7-f0bae089b382';

set @xml = N'<root><r>' + replace(@test,',','</r><r>') + '</r></root>'


Select * from Table1 
where ID in ( select r.value('.','varchar(max)') as item
              from @xml.nodes('//root/r') as records(r)
            );