I'm trying to create a new field in the Order Transactions Table as a Persisted computed column using a Scalar UDF value as the value for the field.
I understand that a requirement for a Persisted column is that the value is deterministic, meaning that the multiple table UDF that I have is non-deterministic as it is not using fields from the source table.
Function:
USE [MyDatabase]
GO
/****** Object: UserDefinedFunction [dbo].[fnCalcOutstandingBalance]
Script Date: 08/10/2018 14:01:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[fnCalcOutstandingBalance](@ItemReferance int)
RETURNS INT
WITH SCHEMABINDING
AS
Begin
DECLARE @AcceptedQty INT
DECLARE @SumOfQty INT
DECLARE @Result INT
SELECT @AcceptedQty =
ISNULL([Accepted Quantity],0)
FROM
dbo.[Order Transactions Table]
WHERE @ItemReferance = [Item Referance]
SELECT @SumOfQty =
ISNULL(sum(Quantity),0)
FROM dbo.[Delivery Table]
GROUP BY [Item Referance]
HAVING @ItemReferance = [Item Referance]
SET @Result = ISNULL(@AcceptedQty,0) - ISNULL(@SumOfQty,0)
return @Result
END
I am looking for a workaround to be able to use the value that is generated from the above function within the Order Transactions Table.
Adding the column:
ALTER TABLE [Order Transactions Table]
ADD CalcOB AS [dbo].[fnCalcOutstandingBalance]([Item Referance]) PERSISTED
I have tested this function and it works as a standalone function call in a select as it should. The problem is that I need this to be used in a computed column without being a virtual column.