我有如下两个不同的表,并且对 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
我有如下两个不同的表,并且对 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
您首先需要一个自定义拆分函数来分隔分隔列表,然后使用它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
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