在SQL中拆分和连接值

时间:2013-03-26 23:48:50

标签: sql-server

我有两个不同的表,如下所示,具有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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

Table1的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