SQL 遇到个问题:不知用循环还是游标做方便一些,求方案
现在遇到一个问题:
如下图,有一个表A主表:
A01(序号) A02( as 出来的字段)
--------------------
a001 ?
a002 ?
a003 ?
....
表B明细表:
B01(序号) B02(内容明细)
----------------------
a001 11
a001 22
a001 33
a002 44
a003 55
a003 66
表B的B02数据没有规律,11,22,33只是测试而已。
现要将表B的B02内容全部取出来( B01和A表的A01关联 )用短线连接组成如下格式放到
表A的A02内容字段里,只要显示即可,A02不是真实存在的字段,as出来即可。
A01 A02
-------------------
a001 11-22-33
a002 44
a003 55-66
同时,我按条件查询A01中a001的明细内容得到如下结果:
a001 11-22-33
不知道大家明白没有?
[解决办法]
--> 测试数据:@表A
declare @表A table([A01] varchar(4))
insert @表A
select 'a001' union all
select 'a002' union all
select 'a003'
--> 测试数据:@表B
declare @表B table([B01] varchar(4),[B02] int)
insert @表B
select 'a001',11 union all
select 'a001',22 union all
select 'a001',33 union all
select 'a002',44 union all
select 'a003',55 union all
select 'a003',66
select a.[A01],b.B02 AS A02 from @表A a
LEFT JOIN
(
select [B01], [B02]=stuff((select '-'+LTRIM([B02])
from @表B where [B01]=t.[B01] for xml path('')), 1, 1, '')
from @表B t group by [B01]
) b ON a.A01=b.B01
/*
A01 A02
---- -----------
a001 11-22-33
a002 44
a003 55-66
*/
create table 表A(A01 varchar(10))
insert into 表A
select 'a001' union all
select 'a002' union all
select 'a003'
create table 表B
(B01 varchar(10),B02 varchar(10))
insert into 表B
select 'a001', '11' union all
select 'a001', '22' union all
select 'a001', '33' union all
select 'a002', '44' union all
select 'a003', '55' union all
select 'a003', '66'
-- 建函数
create function fn_a02
(@b varchar(10))
returns varchar(50)
as
begin
declare @r varchar(50)
select @r=isnull(@r+'-','')+B02
from 表B where B01=@b
return @r
end
select A01,dbo.fn_a02(A01) 'A02'
from 表A
/*
A01 A02
---------- -------------------
a001 11-22-33
a002 44
a003 55-66
(3 row(s) affected)
*/
--按条件查询A01中a001的明细内容
select A01,dbo.fn_a02(A01) 'A02'
from 表A
where A01='a001'
/*
A01 A02
---------- -------------------
a001 11-22-33
(1 row(s) affected)
*/