-- 名稱:mysql遞歸查詢存儲過程(2014-04-05) -- 入:@table 表名[varchar(200)] -- 入:@field 要查詢返回的字段名(例如: name,age,remark)[text] -- 入:@order 返回結果的排序(例如 name desc,age asc)[text] -- 入:@idName 主鍵列名[varchar(200)] -- 入:@pidName父鍵列名[varchar(200)] -- 入:@id 主鍵值[varchar(200)],不能爲null,若是值是null,說明要查詢所有,請本身查詢 -- 入:@upDown 向上級聯仍是向下級聯,1=上 0=下[int] -- 入:@self 是否包含本身 1=是 0=否[int] -- 返回查詢結果集 DROP PROCEDURE IF EXISTS Query_Dg; CREATE PROCEDURE Query_Dg ( IN table_ VARCHAR(200), IN field_ TEXT, IN order_ TEXT, IN idName_ VARCHAR(200), IN pidName_ VARCHAR(200), IN id_ VARCHAR(200), IN upDown_ INT, IN self_ INT ) BEGIN DECLARE _sqlStr VARCHAR(4000); -- 動態sql DECLARE _idParam VARCHAR(4000); -- id存放的變量 DECLARE _idSet VARCHAR(4000); -- 結果 SET @_idSet = ''; -- 查詢id開始 IF(self_ = 1)THEN -- 包含本身 SET @_idSet = id_; END IF; -- 遞歸開始 IF(upDown_ = 1)THEN -- 向上遞歸 SET @_sql = CONCAT('SELECT ',pidName_,' INTO @_idParam FROM ',table_,' WHERE ',idName_,' = ?'); ELSE -- 向下遞歸 SET @_sql = CONCAT('SELECT GROUP_CONCAT(',idName_,') INTO @_idParam FROM ',table_,' WHERE FIND_IN_SET(',pidName_,', ?) > 0'); END IF; SET @_idParam = id_; -- 輸入參數使用時不能 @ PREPARE _sqlStr FROM @_sql; EXECUTE _sqlStr USING @_idParam; WHILE @_idParam IS NOT NULL DO SET @_idSet = CONCAT(@_idSet,',',@_idParam); EXECUTE _sqlStr USING @_idParam; END WHILE; -- 查詢id結束 SET @_sql = CONCAT('SELECT ',field_,' FROM ',table_,' WHERE FIND_IN_SET(',idName_,', ? ) > 0 order by ',order_); -- 查詢 DEALLOCATE PREPARE _sqlStr; -- 解除預編譯 PREPARE _sqlStr FROM @_sql; -- 從新預編譯 EXECUTE _sqlStr USING @_idSet; DEALLOCATE PREPARE _sqlStr; END