RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
遍历BOM表的SQL函数

SQL函数的种类很多,实现的功能也不太一样。下面为您介绍的是用于遍历BOM表的SQL函数,希望可以让您对SQL函数有更多的了解。

成都创新互联欢迎咨询:18980820575,为您提供成都网站建设网页设计及定制高端网站建设服务,成都创新互联网页制作领域10多年,包括成都混凝土搅拌站等多个行业拥有丰富的网站维护经验,选择成都创新互联,为企业锦上添花。

表结构如下:
ptype subptype amount
a  a.120
a  a.2 15
a  a.3 10
a. 1 a.1.1 20
a.1a.1.2  15
a.1 a.1.330
a.2 a.2.110
a.2 a.2.2 20
a.1.1 a.1.1.1 45
a.1.1 a.1.1.2 15
a.2.1 a.2.1.1 20
a.2.2 a.2.2.1 13

 
 
 
  1. create table matgroup(parentgroup varchar(50),childgroup varchar(50), mount float)  
  2.  
  3. insert into matgroup   
  4. select 'a',  'a.1',20  
  5. union select 'a',  'a.2', 15  
  6. union select 'a',  'a.3', 10  
  7. union select 'a.1', 'a.1.1', 20  
  8. union select 'a.1','a.1.2',  15  
  9. union select 'a.1', 'a.1.3',30  
  10. union select 'a.2', 'a.2.1',10  
  11. union select 'a.2', 'a.2.2', 20  
  12. union select 'a.1.1', 'a.1.1.1', 45  
  13. union select 'a.1.1', 'a.1.1.2', 15  
  14. union select 'a.2.1' ,'a.2.1.1', 20  
  15. union select 'a.2.2', 'a.2.2.1', 13  

函数如下:

 
 
 
  1. create FUNCTION fn_aaa (@matgroup varchar(50),@mount int )  
  2. RETURNS @retPLExpand TABLE (parentgroup varchar(50),childgroup varchar(50), mount float)  
  3.  
  4. AS  
  5. BEGIN  
  6. DECLARE @RowsAdded int  
  7. declare @PLExpand Table (parentgroup varchar(50),childgroup varchar(50), mount float,processed tinyint default(0))  
  8.  
  9. INSERT @PLExpand  
  10.  SELECT b.parentgroup,b.childgroup, @mount*b.mount, 0  
  11.  FROM matgroup b   
  12.  WHERE b.parentgroup=@matgroup  
  13. SET @RowsAdded = @@rowcount  
  14.  
  15. -- While new employees were added in the previous iteration  
  16.  
  17. WHILE @RowsAdded > 0  
  18.  
  19. BEGIN  
  20. /*Mark all employee records whose direct reports are going to be   
  21. found in this iteration with processed=1.*/  
  22. UPDATE @PLExpand  
  23. SET processed = 1 
  24. WHERE processed = 0 
  25.  
  26. -- Insert employees who report to employees marked 1.  
  27. INSERT @PLExpand  
  28. SELECT a.parentgroup,a.childgroup,a.mount*b.mount , 0  
  29. FROM matgroup a inner join @PLExpand b on a.parentgroup=b.childgroup  
  30.   where b.processed = 1 
  31.  
  32. SET @RowsAdded = @@rowcount  
  33. /*Mark all employee records whose direct reports have been found  
  34. in this iteration.*/  
  35.  
  36. UPDATE @PLExpand  
  37. SET processed = 2 
  38. WHERE processed = 1 
  39. END  
  40.  
  41. -- copy to the result of the function the required columns  
  42. INSERT @retPLExpand  
  43. SELECT parentgroup,childgroup,mount  
  44. FROM @PLExpand  
  45. RETURN  
  46. END  

调用方法如下:
select * from fn_aaa('a.1')
意思是找出a.1下的所有儿子及孙子.
 

【编辑推荐】

动态sql中使用临时表的实例

Oracle存储过程使用动态SQL

SQL Server删除视图的两种方法

SQL Server视图的使用

sql server表格变量的用法


网站标题:遍历BOM表的SQL函数
当前地址:http://www.jxjierui.cn/article/cccosdd.html