怎么循环查询一个表 用递归吗?
有2张表B1和B2,B1是主表,
B1的BID是对应B2的B2ID,
B1和B2d是一对多的关系,
B2ID下还有以它为父节点的数据,
测试数据如下
B1
BIDsname
1266 JM
1286 DM
......
B2
B2IDSID
1266 DH1500
1266 DH1592
1266 DH1595
DH1500 E89876
DH1500 E89896
联合2表查询,要得到这样的结果:
MainIDSID
1266DH1500
1266DH1592
1266DH1595
DH1500 E89876
DH1500 E89896
这个怎么查?求解
[解决办法]
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-21 11:14:16
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
--Dec 28 2012 20:23:12
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[B1]
if object_id('[B1]') is not null drop table [B1]
go
create table [B1]([BID] varchar(6),[sname] varchar(2))
insert [B1]
select '1266','JM' union all
select '1286','DM'
--> 测试数据:[B2]
if object_id('[B2]') is not null drop table [B2]
go
create table [B2]([B2ID] varchar(6),[SID] varchar(6))
insert [B2]
select '1266','DH1500' union all
select '1266','DH1592' union all
select '1266','DH1595' union all
select 'DH1500','E89876' union all
select 'DH1500','E89896'
--------------开始查询--------------------------
DECLARE @a VARCHAR(10)
SET @a='JM'
;WITH cte AS (
SELECT a.* ,1 [level]
FROM b2 a LEFT JOIN b2 b ON b.SID=a.b2id
WHERE b.b2id IS NULL AND b.SID IS NULL AND a.b2id IN (SELECT bid FROM b1 WHERE [sname]=@a)
),cte2 AS
(
SELECT *
FROM cte
UNION ALL
SELECT a.b2id,a.SID,b.[level]+1 [level]
FROM B2 a INNER JOIN cte2 b ON b.SID=a.b2id
)
SELECT b2id MainID,SID
FROM cte2
----------------结果----------------------------
/*
MainID SID
------ ------
1266 DH1500
1266 DH1592
1266 DH1595
DH1500 E89876
DH1500 E89896
*/
if object_id('[B1]') is not null drop table [B1]
go
create table [B1]([BID] varchar(6),[sname] varchar(2))
insert [B1]
select '1266','JM' union all
select '1286','DM'
if object_id('[B2]') is not null drop table [B2]
go
create table [B2]([B2ID] varchar(6),[SID] varchar(6))
insert [B2]
select '1266','DH1500' union all
select '1266','DH1592' union all
select '1266','DH1595' union all
select 'DH1500','E89876' union all
select 'DH1500','E89896'
go
--1.定义表变量
DECLARE @a VARCHAR(10)
SET @a='JM'
declare @tb table
([B2ID] varchar(6),
[SID] varchar(6),
level int --层级
)
--2.递归开始
insert into @tb
SELECT a.* ,1 [level]
FROM b2 a LEFT JOIN b2 b ON b.SID=a.b2id
WHERE b.b2id IS NULL AND b.SID IS NULL AND a.b2id IN (SELECT bid FROM b1 WHERE [sname]=@a)
--3.递归的过程
while @@ROWCOUNT > 0
begin
insert into @tb
select b.[B2ID],b.[SID],level + 1
from @tb t
inner join B2 b
on b.b2id =t.SID
where not exists(select 1 from @tb t2
where t.level < t2.level)
end
--4.最后查询
SELECT b2id MainID ,SID
FROM @tb
/*
MainIDSID
1266DH1500
1266DH1592
1266DH1595
DH1500E89876
DH1500E89896
*/