『壹』 sql語句中怎麼實現遞歸查詢
在SQL SERVER 2000 中你可以先一些自定義函數,或一些存儲過程,實現遞歸:
select level,TypeName
from ProctType t
START WITH t.ParentID=0
CONNECT BY PRIOR t.ProctTypeID= t.ParentID;
『貳』 sql 怎麼遞歸查詢的方法:
1.創建測試表,createtabletest_connect(idnumber,p_idnumber);
『叄』 SQL中遞歸查詢
CREATE PROCEDURE [dbo].[SetColGroup](@sColItemCode VARCHAR(50),@ReportID VARCHAR(50) )
AS
-- 獲取ItemCode對應的GroupCode,並更新至臨時表中
BEGIN
DECLARE @sSQL VARCHAR(1000)
DECLARE @colGroupCode VARCHAR(50)
DECLARE @SuperColItemCode VARCHAR(50)
DECLARE @colSuperGroupCode VARCHAR(50)
--獲取下一級別的數據(這里的SuperColItemCode實際上是下一級數據)
DECLARE curGroupCodeTmp CURSOR LOCAL FOR
SELECT c.ColGroupCode,b.SuperColItemCode,d.ColGroupCode AS ColSuperGroupCode
FROM dbo.ReportItemCross b
INNER JOIN dbo.ReportColItem c ON b.ColItemCode = c.ColItemCode
INNER JOIN dbo.ReportColItem d ON b.SuperColItemCode = d.ColItemCode
WHERE b.ColItemCode = @sColItemCode AND b.ReportID = @ReportID
OPEN curGroupCodeTmp
FETCH NEXT FROM curGroupCodeTmp
INTO @colGroupCode,@SuperColItemCode,@colSuperGroupCode
WHILE @@FETCH_STATUS = 0
BEGIN
--此處進行實際數據處理
IF(ISNULL(@colGroupCode,'')<>'' AND ISNULL(@colSuperGroupCode,'')<>'')
SET @sSQL = 'update ##tmp set ' + @colSuperGroupCode + ' = ''' + @SuperColItemCode
+ ''' where ' + @colGroupCode + ' = ''' + @sColItemCode + ''''
EXECUTE(@sSQL)
--根據條件判斷是否結束遞歸
IF(ISNULL(@SuperColItemCode,'') <> '')
EXEC SetColGroup @SuperColItemCode,@ReportID
FETCH NEXT FROM curGroupCodeTmp
INTO @colGroupCode,@SuperColItemCode,@colSuperGroupCode
END
CLOSE curGroupCodeTmp
DEALLOCATE curGroupCodeTmp
END
『肆』 關於SQL遞歸查詢問題
我來測一下,等會上傳結果
你還有一個表沒用到。
WITH cte AS (
SELECT RegionID,RegionName,RegionPID FROM [tbRegionTree] WHERE regionPID='01'
UNION ALL
SELECT d.RegionID,d.RegionName,d.RegionPID FROM cte c inner JOIN [tbRegionTree] d ON d.regionPID=c.RegionID
)
SELECT * FROM cte
上面是找到 01 中國的。
下面為非中國的。 條件上處理下
WITH cte AS (
SELECT RegionID,RegionName,RegionPID FROM [tbRegionTree] WHERE regionPID NOT LIKE '01%'
UNION ALL
SELECT d.RegionID,d.RegionName,d.RegionPID FROM cte c inner JOIN [tbRegionTree] d ON d.regionPID=c.RegionID
)
SELECT * FROM cte
『伍』 SQL如何實現遞歸查詢檢測
select * from table_name where id in (select id from table connect by prior id = pid start with id = 你想起始的ID);
(select id from table connect by prior id = pid start with id = 你想起始的ID);
這部分就可以遞歸查詢到所有以某一個父ID下的所有的包含父ID在內的所有ID!