有这么一个需求,当点击某一类别时,我们需要把这一类别下所有的商品都显示出来。
现在我要找出某一类别下的所有子类别:
比如当我点击商城目录时,要把所有的类型ID都找出来,当点击化妆品要把化妆品下所有的ID找到。
用表值函数递归:

1 Create function [dbo].[GetCategroyIDList] (@id int) 2 returns @t table(id int) 3 as 4 begin 5 insert @t select CategoryID from Category where ParentID = @id 6 while @@rowcount > 0 7 insert @t select CategoryID a from Category as a inner join @t as b 8 on a.ParentID = b.id and a.CategoryID not in(select id from @t) 9 return 10 end
当执行:SELECT * from dbo.GetCategroyIDList(2)
就会把ID为5,6的找到
注意:
insert @t select CategoryID a from Category as a inner join @t as b on a.ParentID = b.id and a.CategoryID not in(select id from @t)
此处若把CategoryID换成ParentID
insert @t select CategoryID a from Category as a inner join @t as b on a.ParentID = b.id and a.ParentID not in(select id from @t)
则只取到下一级的所有ID
给这个表生成有规律的代码
比如AAA,生成一个以AAA开头,后面跟21位数字的代码。AAA----------01

1 ALTER function [dbo].[CreateCode]( 2 @ebaystockflag varchar(20)--规则字母 3 ) 4 returns varchar(100) 5 AS 6 BEGIN 7 declare @dt CHAR(8) 8 declare @flag varchar(20) 9 set @flag=@ebaystockflag 10 set @dt=CONVERT(CHAR(8),GETDATE(),112) 11 declare @max varchar(100) 12 SELECT @max=MAX(CategoryID) 13 FROM Category WITH(XLOCK,PAGLOCK) 14 WHERE CategoryID like @flag+'%' 15 16 set @max=isnull(@max, @flag+'100000000000000000000')--查不到结果给个默认值 17 declare @a varchar(100) 18 declare @num varchar(30) 19 declare @ordernum varchar(30) 20 set @a=Convert(varchar,right(@max,len(@max)-3))--截取数字部分 21 22 SET @num = CONVERT(varchar(30),CONVERT(numeric(24,0),@a)+1) 23 return @flag+@num 24 END
执行
SELECT dbo.CreateCode('Arl')
生成Arl100000000000000000001