2013-03-26 53 views
2

我有兩個不同的表,如下所示,並且具有sql查詢的特定要求。拆分並連接SQL中的值

Table1: 
Name RuleNumber 
Tom 1,2 
Pete 1,3 

Table2: 
RuleNumber Description 
1   Rule1 
2   Rule2 
3   Rule3 

我怎樣才能得到一個SQL查詢結果類似下面

Name Description 
Tom  Rule1, Rule2 
Pete Rule1, Rule3 

回答

3

你首先需要一個自定義分割功能,以獨立的分隔列表,然後使用FOR XML PATH的描述結合起來。這裏是你的最終查詢

select t1.Name, 
     STUFF((SELECT ',' + Description 
       FROM table2 AS t2 
       WHERE t2.ruleNumber in (select s from dbo.fn_split(t1.RuleNumber, ',')) 
     ORDER BY ruleNumber 
     FOR XML PATH('')), 1, 1, '') as 'Description' 
from table1 t1 

這是分割函數的代碼。

create function [dbo].[fn_Split] 
(
    @String  varchar(8000) , 
    @Delimiter varchar(10) 
) 
returns @tbl table (s varchar(1000)) 
as 

begin 
declare @i int , 
    @j int 
    select @i = 1 
    while @i <= len(@String) 
    begin 
     select @j = charindex(@Delimiter, @String, @i) 
     if @j = 0 
     begin 
      select @j = len(@String) + 1 
     end 
     insert @tbl select substring(@String, @i, @j - @i) 
     select @i = @j + len(@Delimiter) 
    end 
    return 
end 
+0

太棒了。我只是試過這個,它實際上帶回了我想要的。非常感謝你的幫助。 – hrishi 2013-03-27 00:38:12

+0

謝謝,很高興幫助!這個小分裂功能可以派上用場,我用了很多年。 – Nate 2013-03-27 05:31:24

0

的表1的RuleNumber如何有一個以上的價值?它是一個字符串嗎?我會假設它是:

Name/RuleNumber 
Tom/1 
Tom/2 

隨後,查詢將是:

select 
    Name, 
    ( 
    select Description 
    from Table2 as t2 
    where t1.ruleNumber = t2.ruleNumber 
) as Description 
from 
    table1 as t1 
+0

對不起,這與JOIN類似,並沒有達到結果。因爲Table1中的值是用逗號分隔的多個值。在Table2中它們是獨一無二的。 – hrishi 2013-03-27 00:34:22