Sql的遞迴查詢

2021-07-14 14:33:31 字數 3306 閱讀 3144

sql遞迴原理

遞迴最少包括兩個查詢(也被稱為成員)。第乙個查詢為定點成員,定點成員只是乙個返回有效表的查詢,用於遞迴的基礎或定位點。

第二個查詢被稱為遞迴成員,使該查詢成為遞迴成員的是對遞迴引用時觸發(遞迴表.id與該錶的pid)。在邏輯上,可以將其理解為是前乙個查詢語句的子集。

遞迴查詢沒有顯式的遞迴終止條件,只有當第二個遞迴查詢返回空結果集或是超出了遞迴次數的最大限制時才停止遞迴。遞迴次數上限的方法是使用maxrecurion。

1、sqlserver2005版本的sql如下:

比如乙個表,有id和pid欄位,id是主鍵,pid表示它的上級節點,表結構和資料:

create

table [aaa](

[id] [int] null,

[pid] [int] null,

[name] [nchar](10))go

insert

into aaa values(1,0,'a')

insert

into aaa values(2,0,'b')

insert

into aaa values(3,1,'c')

insert

into aaa values(4,1,'d')

insert

into aaa values(5,2,'e')

insert

into aaa values(6,3,'f')

insert

into aaa values(7,3,'g')

insert

into aaa values(8,4,'h')

go

查詢出1結點的所有子結點

--

--結果包含1這條記錄,如果不想包含,可以在最後加上:where id <> 1

with my1 as(select * from aaa where id = 1

union

allselect aaa.* from my1, aaa where my1.id = aaa.pid

)select * from my1

查詢出8結點的所有父結點

with my1 as(select * from aaa where id = 8

union

allselect aaa.* from my1, aaa where my1.pid = aaa.id

)select * from my1;

遞迴刪除1結點和所有子結點的語句:

with my1 as(select * from aaa where id = 1

union

allselect aaa.* from my1, aaa where my1.id = aaa.pid

)delete

from aaa where

exists (select id from my1 where my1.id = aaa.id)

2、sql遞迴案例:

假設有個銷售表如下:

create

table [tb](

[qj] [int] null, -- 月份,本測試假設從1月份開始,並且資料都是連續的月份,中間沒有隔斷

[je] [int] null, -- 本月銷售實際金額

[rwe] [int] null, -- 本月銷售任務額

[fld] [float] null -- 本月金額大於任務額時的返利點,返利額為je*fld

) on [primary]

現在要求計算每個月的返利金額,規則如下:

1月份銷售金額大於任務額 返利額=金額*返利點

2月份銷售金額大於任務額 返利額=(金額-1月份返利額)*返利點

3月份銷售金額大於任務額 返利額=(金額-1,2月份返利額)*返利點

以後月份依次類推,銷售額小於任務額時,返利為0

具體的sql如下:

with my1 as (

select *,case

when je > rwe then (je * fld) else

0end fle, cast(0

asfloat) tmp

from tb

where qj = 1

union

allselect tb.*,case

when tb.je > tb.rwe then (tb.je - my1.fle -my1.tmp) * tb.fld else

0end fle,

my1.fle + my1.tmp tmp --用於累加前面月份的返利

from my1,tb

where tb.qj = my1.qj + 1

)select * from my1

3、表示式遞迴查詢

with cte(id,parentid,text)

as (--父項

select id,parentid,text

from treeview where parentid = 450

union all

--遞迴結果集中的下級

select t.id,t.parentid,t.text

from treeview as t

inner join cte as c on

t.parentid = c.id

) select id,parentid,text

from cte

with cte(id,parentid,text)

as (--下級父項

select id,parentid,text

from treeview where

id = 450

union all

--遞迴結果集中的父項

select t.id,t.parentid,t.text

from treeview as t

inner join cte as c on

t.id = c.parentid

) select id,parentid,text

from cte

遞迴查詢SQL

lz需要的修改自己為對應的,csdn sqlserve大版主 鄒建 我轉貼並且完善一下 測試資料 create table tb id char 3 pid char 3 name nvarchar 10 insert tb select 001 null 山東省 union all select ...

SQL遞迴查詢

create table t bid int,p bid int insert into t select 1,null union all select 2,1 union all select 3,1 union all select 4,3 union all select 5,4 union...

SQL 遞迴查詢

create proc proc tree node int asbegin declare i int set i 0 set nocount on drop table res create table res node int,child int,weight int,op int inser...