CREATE function BOM1(@parent VARCHAR(20))returns @temptable table(LEVEL tinyint,主件 Nvarchar(20),子件 Nvarchar(20), 数量 numeric(9,3),替代料 Nvarchar(20),原子件 Nvarchar(20), OrderID numeric(9,3) ) asbegin declare @LEVEL int set @LEVEL=1 insert into @temptable select @LEVEL,a.主件,a.子件,a.数量,(CASE WHEN b.主件 IS NULL THEN NULL ELSE '*' END) AS 替代料, a.子件 AS 原子件, 0 AS OrderID FROM BOM a LEFT JOIN BOM替代料表 b ON (a.主件 = b.主件 OR b.主件 = '*') AND a.子件 = b.原子件 where a.主件=@parentunion all SELECT @LEVEL, a.主件, b.新子件 AS 子件, b.数量 AS 数量, '替代' AS 替代料,a.子件 AS 原子件, 1 AS OrderID FROM BOM a INNER JOIN BOM替代料表 b ON (a.主件 = b.主件 OR b.主件 = '*') AND a.子件 = b.原子件 --where (b.主件=@parent ) while @@rowcount>0 begin set @LEVEL=@LEVEL+1 insert @temptable select @LEVEL,a.主件,a.子件,a.数量,(CASE WHEN b.主件 IS NULL THEN NULL ELSE '*' END) AS 替代料, a.子件 AS 原子件, 0 AS OrderID FROM BOM a LEFT JOIN BOM替代料表 b ON (a.主件 = b.主件 OR b.主件 = '*') AND a.子件 = b.原子件, @temptable BB where a.主件=BB.子件 and BB.LEVEL=@LEVEL-1 union all SELECT @LEVEL, a.主件, b.新子件 AS 子件, b.数量 AS 数量, '替代' AS 替代料,a.子件 AS 原子件, 1 AS OrderID FROM BOM a INNER JOIN BOM替代料表 b ON (a.主件 = b.主件 OR b.主件 = '*') AND a.子件 = b.原子件 , @temptable BB where BB.子件=a.主件 AND BB.LEVEL=@LEVEL-1 endreturnendSELECT replicate('.',LEVEL*1)+ltrim(str(LEVEL)),*FROM BOM1('A')order by LEVEL,主件,原子件,OrderID --结果是出来了,但排序后的结果不对