How can I write a function to compute a column value as described in this picture?
This is the code I have tried:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION RunningBal
(
-- Add the parameters for the function here
@Dr INT,
@Cr INT,
@Code NVARCHAR(5)
)
RETURNS INT
AS
BEGIN
-- Declare the return variable here
DECLARE @CurrentRunningBal INT
-- Add the T-SQL statements to compute the return value here
DECLARE @PreviouBal INT
SET @PreviouBal = (SELECT TOP(1) [RunningBal] FROM Test WHERE Code = @Code ORDER BY ID DESC)
if(@PreviouBal IS NULL)
SET @PreviouBal = 0
SET @CurrentRunningBal = @PreviouBal + @Dr - @Cr
-- Return the result of the function
RETURN @CurrentRunningBal
END
GO
When I try to execute this, I get the following error and have no clue how to solve it.