2014-05-23 94 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))+',%' ; 
相關問題