--测试数据
CREATE TABLE tb(ID char(3),PID char(3),Name nvarchar(10))
INSERT tb SELECT '001',NULL ,'山东省'
UNION ALL SELECT '002','001','烟台市'
UNION ALL SELECT '004','002','招远市'
UNION ALL SELECT '003','001','青岛市'
UNION ALL SELECT '005',NULL ,'四会市'
UNION ALL SELECT '006','005','清远市'
UNION ALL SELECT '007','006','小分市'
GO--查询指定节点及其所有子节点的函数
CREATE FUNCTION [dbo].[f_Cid](@ID char(3))
RETURNS INT
AS
BEGIN
DECLARE @TOTAL INT
DECLARE @Level INT
DECLARE @t_Level TABLE(ID char(3),Level int)
SET @Level=1
SET @TOTAL=0
INSERT @t_Level SELECT @ID,@Level
WHILE @@ROWCOUNT>0
BEGIN
SET @Level=@Level+1
INSERT @t_Level SELECT a.ID,@Level
FROM tb a,@t_Level b
WHERE a.PID=b.ID
AND b.Level=@Level-1
END
SELECT @TOTAL=COUNT(*) FROM @t_LEVEL
RETURN @TOTAL
END--结果
SELECT Id,Total=dbo.f_Cid(Id)
FROM tb

解决方案 »

  1.   

    没有细看.
    只知道将代码复制到查询分析器里有错误.==============================以上代码我在MYSQL-FRONT3。2中运行出错~~~阁下是指SQLSERVER吧?
      

  2.   

    对照着mysql5的语法帮助,自己转换一下吧
      

  3.   

    对照着mysql5的语法帮助,自己转换一下吧
    ---------------------------------------
    已经对着MYSQL5研究的两天了。
    就一个declare临时表变量也出错。郁闷 ~~~~
      

  4.   

    set names gb2312;
    CREATE TABLE tb(
    ID char(3),
    PID char(3),
    Name varchar(10)) 
    default charset=gb2312 
    engine=myisam;INSERT tb SELECT '001',NULL ,'山东省'
    UNION ALL SELECT '002','001','烟台市'
    UNION ALL SELECT '004','002','招远市'
    UNION ALL SELECT '003','001','青岛市'
    UNION ALL SELECT '005',NULL ,'四会市'
    UNION ALL SELECT '006','005','清远市'
    UNION ALL SELECT '007','006','小分市';
    DELIMITER $$DROP FUNCTION IF EXISTS `test2`.`fn_level`$$CREATE DEFINER=`root`@`localhost` FUNCTION `fn_level`(id char(3)) RETURNS int(11)
    BEGIN
      declare v_level int default 1;
      declare total int default 0;
      declare cnt int default 0;
      create temporary table if not exists t_Level (ID char(3),`Level` int);
      insert into t_Level select id,v_level;
      select found_rows() into cnt;
      while cnt>0 
      do
        SET v_level = v_level+1;
        insert into t_Level select tb.ID,v_level
        from tb,t_Level where tb.PID=t_Level.ID 
        and t_Level.Level=v_level-1;
      end while;
      select count(*) from t_Level into total;
      RETURN total;
    END$$DELIMITER ;
      

  5.   

    DELIMITER $$DROP FUNCTION IF EXISTS `test2`.`fn_level`$$CREATE DEFINER=`root`@`localhost` FUNCTION `fn_level`(id char(3)) RETURNS int(11)
    BEGIN
    declare v_level int default 1;
    declare total int default 0;
    create temporary table if not exists t_Level (ID char(3),`Level` int);
    insert into t_Level select id,v_level;
    这里改一下。
    while row_count()<>-1
    do
    SET v_level = v_level+1;
    insert into t_Level select tb.ID,v_level
    from tb,t_Level where tb.PID=t_Level.ID
    and t_Level.Level=v_level-1;
    end while;
    select count(*) from t_Level into total;
    RETURN total;
    END$$DELIMITER ;