2016-05-21 125 views
0

我想通过nvarchar值uniqueidentifier。从字符串转换为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条件。

请帮我解决这个问题。

+0

不能使用字符串包含可变像'“X”,“Y”,“Z” '在in子句中,并认为它会获取3个值。它会尝试找到一个值,“X”,“Y”,“Z”。您必须创建动态SQL,或者使用某种表结构,如表变量。 –

回答

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

尝试......

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) 
      ); 
相关问题