﻿USE [FabApprovalSystem]
GO
	/****** Object:  UserDefinedFunction [dbo].[fnGetScrapCost]    Script Date: 11/21/2024 11:31:55 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	-- =============================================
	-- Author:		<Author,,Name>
	-- Create date: <Create Date, ,>
	-- Description:	<Description, ,>
	-- =============================================
	CREATE FUNCTION [dbo].[fnGetScrapCost] (
		-- Add the parameters for the function here
		@IssueID INT
	) RETURNS FLOAT AS BEGIN -- Declare the return variable here
	DECLARE @WaferCount INT DECLARE @DieCount INT DECLARE @ScrapWaferCount INT DECLARE @ScrapCost FLOAT DECLARE @ScrapDieCount INT DECLARE @TotalCost FLOAT DECLARE @PerWaferCost FLOAT DECLARE @PerDieCost FLOAT DECLARE @TotalScrapCost FLOAT DECLARE @LotStatusOptionID INT
SET
	@TotalScrapCost = 0 DECLARE ScrapCostCursor CURSOR FOR
SELECT
	L.TotalCost,
	L.WaferCount,
	L.DieCount,
	S.ScrapCount,
	L.LotStatusOptionID
FROM
	Lot L
	INNER JOIN ScrapLot S ON L.IssueID = S.IssueID
	AND L.LotNumber = S.LotNo
WHERE
	L.IssueID = @IssueID OPEN ScrapCostCursor FETCH NEXT
FROM
	ScrapCostCursor INTO @TotalCost,
	@WaferCount,
	@DieCount,
	@ScrapWaferCount,
	@LotStatusOptionID WHILE @ @FETCH_STATUS = 0 BEGIN
SET
	@PerWaferCost = 0
SET
	@PerDieCost = 0 IF @ScrapWaferCount > 0
	AND @WaferCount > 0
	AND @TotalCost > 0 BEGIN
SET
	@PerWaferCost = @TotalCost / @WaferCount;

SET
	@ScrapCost = @ScrapWaferCount * @PerWaferCost --PRINT @ScrapCost
SET
	@TotalScrapCost = @TotalScrapCost + @ScrapCost
END
ELSE IF @DieCount > 0
AND @LotStatusOptionID = 2 BEGIN
SET
	@ScrapCost = @TotalCost
SET
	@TotalScrapCost = @TotalScrapCost + @ScrapCost
END FETCH NEXT
FROM
	ScrapCostCursor INTO @TotalCost,
	@WaferCount,
	@ScrapDieCount,
	@ScrapWaferCount,
	@LotStatusOptionID
END CLOSE ScrapCostCursor DEALLOCATE ScrapCostCursor -- Return the result of the function
RETURN @TotalScrapCost
END
GO