2014-05-23 43 views
0

SQL语句:通过逗号deligma字符串IN子句中的SQL Server

(select top 1 [egrp_name] from [Enotify Group] where [egrp_id] in (a.grp_id)) 

a.grp_id电子值为'0,1145',我得到错误

Conversion failed when converting the varchar value '0,1145' to data type int. 

可有人告诉我,我怎么能在上面的情况下将'0,1145'更改为0,1145,所以我的查询确实有效,并且如果他们有任何其他方式可以执行此操作

回答

1

您可以使用拆分字符串函数来更改将逗号分隔的字符串转换为表格。分割字符串函数的

select top(1) [egrp_name] 
from [Enotify Group] 
where [egrp_id] in (
        select Value 
        from dbo.SplitInts(a.grp_id) 
        ); 

一个版本,如果你喜欢,你可以使用:

create function dbo.SplitInts(@Values nvarchar(max)) returns table with schemabinding 
as 
return 
( 
    select T2.X.value(N'.', N'int') as Value 
    from (select cast(N'<?X '+replace(@Values, N',', N'?><?X ') + N'?>' as xml).query(N'.')) as T1(X) 
    cross apply T1.X.nodes(N'/processing-instruction("X")') as T2(X) 
); 

或者您可以使用like

select top(1) [egrp_name] 
from [Enotify Group] 
where ','+a.grp_id +',' like '%,'+cast(egrp_id as varchar(11))+',%' ; 
相关问题