当前位置: 代码迷 >> Sql Server >> MS SQL2000中,求SQL语句。该如何处理
  详细解决方案

MS SQL2000中,求SQL语句。该如何处理

热度:94   发布时间:2016-04-24 10:59:56.0
MS SQL2000中,求SQL语句。急。。。。


tab1
pid  pname
1    层板
2    顶板
3    中侧板

tab2
id   pid   pcode
1    1     993029
2    1     993030
3    1     993031

4    2     311021
5    2     311022

6    3     223345
7    3     223346
8    3     223347
9    3     223348

MS SQL2000中,如何写一个SQL语句,执行后,查询结果如下:

pid  pname   allcode
1    层板     993029,993030,993031
2    顶板     311021,311022
3    中侧板   223345,223346,223347,223348


------解决方案--------------------
;with tab1(pid , pname) as
(
select 1,'层板'
union all select 2,'顶板'
union all select 3,'中侧板'
),
tab2(id ,  pid ,  pcode) as
(
select 1,1,'993029'
union all select 2,1,'993030'
union all select 3,1,'993031'
union all select 4,2,'311021'
union all select 5,2,'311022'
union all select 6,3,'223345'
union all select 7,3,'223346'
union all select 8,3,'223347'
union all select 9,3,'223348'
),cte as
(
select a.*,b.pname from tab2 a left join tab1 b on a.pid=b.pid
)

select a.pid,a.pname,
stuff((select ','+pcode from cte b 
       where b.pid=a.pid 
       for xml path('')),1,1,'') 'pcode'
from cte a
group by  a.pid,a.pname

/*
pid pname pcode
1 层板 993029,993030,993031
2 顶板 311021,311022
3 中侧板 223345,223346,223347,223348
*/


------解决方案--------------------
2000不支持xml path ,所以用函数来实现,应该没有什么更好的办法了:

create table tab1(pid int,  pname varchar(100));

insert into tab1
select 1,    '层板' union all
select 2,    '顶板' union all
select 3,    '中侧板'

create table tab2(id int,  pid int, pcode varchar(100))

insert into tab2
select 1,    1,     '993029' union all
select 2,    1,     '993030' union all
select 3,    1,     '993031' union all
select 4,    2,     '311021' union all
select 5,    2,     '311022' union all
select 6,    3,     '223345' union all
select 7,    3,     '223346' union all
select 8,    3,     '223347' union all
select 9,    3,     '223348'
go




--drop function dbo.fn_mergeSTr


create function dbo.fn_mergeSTR(@pid int,@split varchar(10))  
returns varchar(300)  
as  
begin  
    declare @str varchar(300);  
      
    set @str = '';  
      
    select @str = @str + pcode + @split  
    from tab2  
    where pid = @pid  
      
    set @str = left(@str , len(@str) - LEN(@split) )  
      
    return @str   --返回值   
end  
go  


select distinct
       t1.pid,
       t1.pname,
       
       dbo.fn_mergeSTR(t1.pid,',') as str
from tab1 t1
/*
pid pname pcode
1 层板 993029,993030,993031
2 顶板 311021,311022
3 中侧板 223345,223346,223347,223348
*/

------解决方案--------------------
sql 2000就得写函数了:


create table tab1(pid int, pname varchar(10)) 
insert into tab1
select 1,'层板'
union all select 2,'顶板'
  相关解决方案