日期:2014-05-18  浏览次数:20535 次

请教一个多值关联查询的问题!
类型表:
KeyID       Type_Name
    1               广州
    2               深圳
    3               中山
    4               厦门
    5               珠海

A表
KeyID       V_Type
    1             2,3,4  
    2             2,5
    3             3
其中KeyID为主键,V_Type字段的值可以为空或多值,V_Type的值与类型表主键关联,现需要实现A表与类型表关联查询,需实现一下效果:
KeyID       V_Type
    1           深圳,中山,厦门
    2           深圳,珠海
    3           中山
(除了自己写函数,还有什么更好,效率更高的办法?)

------解决方案--------------------
create table ta(KeyID int, [Type_Name] nvarchar(5))
insert ta select 1, '广州 '
union all select 2, '深圳 '
union all select 3, '中山 '
union all select 4, '厦门 '
union all select 5, '珠海 '
go
create table tb(KeyID int, V_Type nvarchar(20))
insert tb select 1, '2,3,4 '
union all select 2, '2,5 '
union all select 3, '3 '
go


create function test_f(@v_type nvarchar(20))
returns nvarchar(20)
as
begin
declare @s nvarchar(20)
select @s=isnull(@s+ ', ', ' ')+[Type_Name] from ta where charindex( ', '+rtrim(KeyID)+ ', ', ', '+@v_type+ ', ')> 0
return @s
end
go

select KeyID,[V_Type]=dbo.test_f(V_Type) from tb

--drop table ta,tb
--drop function test_f
KeyID V_Type
----------- --------------------
1 深圳,中山,厦门
2 深圳,珠海
3 中山

(所影响的行数为 3 行)