mssql多級查詢 CTE遞迴

2021-06-23 09:53:47 字數 1934 閱讀 9650

最近做乙個製造業專案中涉及到打包問題,其模式為: 乙個a->b->c->...可以無限打包,a包含b,b包含c等。

之間遇到了:

1、打包後包裹數量需要更新,更新時必須對他的父級包號也進行更新,所以必須查詢出某個包號對應的所有父級包號;

2、拆包(將包裹拆除,希望把a下面的包裹號也連同一起拆除,這樣必須查詢出某個包號對應的所有子級包號。

後面解決方案:

--建立簡單測試打包表

create table t_pack

( id int identity(1,1) primary key,

packno varchar(40) not null,

parentpackno varchar(40) null,

packquantity int

)

插入資料方便測試:
insert into t_pack(packno, parentpackno,packquantity) values('pack_001',null,1)

insert into t_pack(packno, parentpackno,packquantity) values('pack_002',null,1)

insert into t_pack(packno, parentpackno,packquantity) values('pack_003',null,5)

insert into t_pack(packno, parentpackno,packquantity) values('pack_004','pack_003',1)

insert into t_pack(packno, parentpackno,packquantity) values('pack_005','pack_003',4)

insert into t_pack(packno, parentpackno,packquantity) values('pack_006','pack_005',2)

insert into t_pack(packno, parentpackno,packquantity) values('pack_007','pack_005',2)

insert into t_pack(packno, parentpackno,packquantity) values('pack_009',null, 7)

insert into t_pack(packno, parentpackno,packquantity) values('pack_010', null,4)

資料表:可以看出:pack_007的父級有 pack_005 和pack_003兩個

查詢所有的父級包號及本身:

with ctegetparent as  

( select * from t_pack where packno=@packno --傳入包號'pack_007'

union all

(select a.* from t_pack as a inner join

ctegetparent as b on a.packno=b.parentpackno

) select * from ctegetparent

查詢結果

查詢所有的子級包號及本身:

with area as( 

select * from t_pack where packno=@packno --傳入包號'pack_003'

union all 

select a.* from t_pack a join area b on a.parentpackno=b.packno 

)select * from area

後面更新數量就通過游標迴圈id進行更新。。。。。。

CTE遞迴查詢

匯入資料 create table dbo.dt user userid int,managerid int,name nvarchar 10 insert into dbo.dt user select 1,1,n boss union allselect 11,1,n a1 union alls...

sql server利用cte遞迴查詢

with cte id,name,parent id as select id,name,parent id from sc district where name 巴中市 union all select sd.id,sd.name,sd.parent id from sc district sd...

Sql Server 使用CTE實現遞迴查詢

遞迴cte是sql server 2005中重要的增強之一。一般我們在處理樹,圖和層次結構的問題時需要用到遞迴查詢。cte的語法如下 1with cte as2 3select empid,reportto,fname from employ where empid 1 4union all5 se...