检查 Bom 分录物料的有效性,递归 SQL 查询( 编号:20110630A0957 )

此存储过程用于检查在物料清单(BOM)中欲添加的分录物料是否已存在于其父级物料中,通过递归查询确保物料的唯一性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有如下数据,其中 itemId 相当于 entryItemId 的父 id,

目标:检查指定 id 的所有父节点,是否有它自己本身。

 

 

代码如下:

 

 

 

存储过程 :

 

 

 

最终的版本:

 

 

上面的也不是最终版,下面也有修改:


USE [db_NLMRPII]
GO
/****** 对象:  StoredProcedure [dbo].[p_bomEntry_item_validCheck]    脚本日期: 07/03/2011 10:48:44 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	检查欲添加的分录物料是否合法,
--                  即,其在自己的 N 级父物料中是否已经存在。
-- =============================================

-- 使用示例

-- DECLARE	@return_value int
-- 			
-- EXEC @return_value = [dbo].[p_bomEntry_item_validCheck]
-- 	 @itemId =  29960
-- 	,@entryItemId = 29960 -- Need to check
-- 			
-- select @return_value


ALTER PROCEDURE [dbo].[p_bomEntry_item_validCheck]
	-- Add the parameters for the stored procedure here
	 @itemId int
	,@entryItemId int -- 需要检查的物料
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;


	declare @tempTable table( itemId int );
	declare @ErrCounter int ;
	declare @ErrCounterMax int ;
	declare @records int ; -- 记录数

	set @ErrCounter = 0 ;
	set @ErrCounterMax = 10  ;
	set @records = 0  ;

	-- 组织关系表
	with a as ( 
		select t1.f_intBomId as bomId 
			, t1.f_intItemId as itemId
			, t2.f_intItemId as entryItemId 
		from v_bom t1 left join v_bomEntry t2
		on t1.f_intBomId = t2.f_intBomId )	
	
	-- 将该BOM的物料ID存入,防止分录物料与BOM物料重复。
	insert @tempTable values( @itemId )

	-- 将该 BOM 物料的所有父物料存入,进入下面循环。
	insert @tempTable select itemId from a where entryItemId = @itemId

	-- 每层循环将临时表中的所有父物料存入(不包含表中已经存在的物料)。
	while @@rowcount > 0 and @ErrCounter <= @ErrCounterMax
	begin

		set @ErrCounter = @ErrCounter + 1 ;
		
		with b as ( 

			select t1.f_intBomId as bomId 
				, t1.f_intItemId as itemId
				, t2.f_intItemId as entryItemId 
			from v_bom t1 left join v_bomEntry t2
			on t1.f_intBomId = t2.f_intBomId
		)	

		insert @tempTable select itemId from b 
			where entryItemId in ( select * from @tempTable )
				and itemId not in ( select * from @tempTable )
	end
		

	-- 查询临时表中是否有欲添加的物料ID,有则无效。
	select @records = count(*) from @tempTable where itemId = @entryItemId
		
	return @records

END



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值