(两种结构,两种方式)根据主表ID,查询子表的信息并用逗号分隔 MSSQL Server

  •  结构一
根据主表ID,查询子表的信息并用逗号分隔
详情如下:

1主表:
select * from subcom

ID Name   
1 总公司 
2 公司1   
3 公司2   

2子表
select * from SubcomEarningOrg

ID SubCom EarningOrg
1 1 258
2 1 260
3 1 262
4 1 263
5 1 265
6 1 266
7 1 267
8 1 268
9 1 271
10 1 272
11 2 408
12 3 422

其中subcom 为主表的ID ,EarningOrg为另外一张基础表的ID。


基础表  
select * from BaseData

ID Name
258 一车队
260 二车队
262 三车队
263 四车队
265 五车队
266 六车队
267 七车队
268 八车队
271 九车队
272 十车队

现在要求查询出主表所对应的子表的所有在一条主表对应的记录并用逗号隔开如

主表Name 基础Name   
总公司 一车队,二车队,三车队,四车队,五车队,六车队,七车队,八车队,九车队,十车队

答: 这样来实现

create table t(id int,name nvarchar(30))
 
create table t1(id int,SubCom int, EarningOrg int)
 
create table t2(id int, name nvarchar(30))
  
insert into t
  
select 1'总公司' union all  
select 2'公司1' union all  
select 3'公司2'
insert into t1
select 11258 union all
select 21 ,260 union all
select 31 ,262 union all
select 41 ,263 union all
select 51 ,265 union all
select 61 ,266 union all
select 71 ,267 union all
select 81 ,268 union all
select 91 ,271 union all
select 101272 union all
select 112408 union all
select 123422  
insert into t2
select 258'一车队' union all  
select 260'二车队' union all
select 262'三车队' union all
select 263'四车队' union all
select 265'五车队' union all
select 266'六车队' union all
select 267'七车队' union all
select 268'八车队' union all
select 271'九车队' union all
select 272'十车队'
create function gY(@id as int)
returns nvarchar(100)
as  
begin
 
declare @s nvarchar(100)
 
set @s=''
 
select @s=@s+ISNULL(t2.name+',',''from t1,t2 where t1.SubCom=@id and t1.EarningOrg=t2.id
 
IF @s<>''
  
return substring(@s,1,len(@s)-1)
 
return ''   
end
go  
select name,基础name=dbo.gY(id) from t where dbo.gY(id)<>''
drop table t
drop table t1
drop table t2
  •  结构二
根据主表ID,查询子表的信息并用逗号分隔
详情如下:

1主表:
select * from subcom

ID Name   subid
1 总公司  258,260,262
2 公司1   408
3 公司2   422

2子表
select * from BaseData

ID Name
258 一车队
260 二车队
262 三车队
263 四车队
265 五车队
266 六车队
267 七车队
268 八车队
271 九车队
272 十车队

现在要求查询出主表所对应的子表的所有在一条主表对应的记录并用逗号隔开如

主表Name 基础Name   
总公司 一车队,二车队,三车队

SQL函数实现

/*
详细设计构思:http://www.cnblogs.com/chengulv/archive/2011/09/09/2172634.html
根据主键串 获得用逗号分割的其他字段内容。(如:总经理,业务员,仓库)
*/
CREATE   PROCEDURE [dbo].[sp_comma]
    @r nvarchar(4000) output,
    @showField nvarchar(255),  --显示的字段名 如: 'groupName'
    @tableName nvarchar(255),  --表名     如: 's_adminGroup'
    @whereField nvarchar(255), --条件字段名   如: 'iid'
    @whereValue nvarchar(255), --条件字段值   如: '2,7'
    @split nvarchar(2= ','
AS
declare @sql nvarchar(4000)
set @sql = 'set @g='''';select @g = @g + isnull(' + @showField + ' + ''' + @split + ''','''') from '+ @tableName + ' where '+ @whereField + ' in ('+ @whereValue + ');if @g<>'''' set @g = substring(@g,1,len(@g)-1)'
exec sp_executesql @sql, N'@g nvarchar(2000) output'@r output
--if @gname<>'' set @gname = substring(@gname,1,len(@gname)-1)
 

 




GO
原文地址:https://www.cnblogs.com/chengulv/p/2172634.html