I am trying to streamline the following T-SQL user function to be used within a persisted computed column in one of my table. I understand that I can use a calculated column within a view among other methods but for various reasons due to user requirement this column is best implemented as such.
However in order for this scalar function to be used in a computer column, I am trying to make it as efficient and stream line as possible. There are parts of the function with the following SELECT COUNT
statement
SELECT COUNT([JunctionID])
FROM dbo.ApplicationJunctionT
WHERE [AccountID] = @AccountID
AND [Outcome] IS NULL
AND [Change Account Status] IS NULL
that I use repeatedly and I'm wondering if there is a better way to reorganize this function for efficiency. I did try using CTE to wrap this select statement up but continually run into syntax issues and have since given up on that idea.
ALTER FUNCTION [dbo].[fnAccountReadyByID_Test]
(@JunctID INT = Null,
@AccountID VARCHAR(20) = NULL)
RETURNS VARCHAR(10)
AS
BEGIN
DECLARE @FamilyAccountReady as varchar(10),
@TotalFamily as INT;
SET @TotalFamily = (SELECT COUNT([JunctionID])
FROM dbo.ApplicationJunctionT
WHERE [AccountID] = @AccountID
AND [Outcome] IS NULL
AND [Change Account Status] IS NULL)
IF @TotalFamily = 1
SET @FamilyAccountReady = (SELECT AccountStatus
FROM dbo.ApplicationJunctionT
WHERE JunctionID = @JunctID)
ELSE
SET @FamilyAccountReady = (CASE
WHEN (SELECT COUNT([JunctionID])
FROM dbo.ApplicationJunctionT
WHERE [AccountID] = @AccountID
AND [Outcome] IS NULL
AND [Change Account Status] IS NULL
AND [AccountStatus] = '-') > 0
THEN '-'
WHEN (SELECT COUNT([JunctionID])
FROM dbo.ApplicationJunctionT
WHERE [AccountID] = @AccountID
AND [Outcome] IS NULL
AND [Change Account Status] IS NULL
AND [AccountStatus] = 'Frozen') > 0
THEN 'Frozen'
WHEN (SELECT COUNT([JunctionID])
FROM dbo.ApplicationJunctionT
WHERE [AccountID] = @AccountID
AND [Outcome] IS NULL
AND [Change Account Status] IS NULL
AND [AccountStatus] = 'Closed') > 0
THEN 'Closed'
WHEN (SELECT COUNT([JunctionID])
FROM dbo.ApplicationJunctionT
WHERE [AccountID] = @AccountID
AND [Outcome] IS NULL
AND [Change Account Status] IS NULL
AND [AccountStatus] = 'Tentative') > 0
THEN 'Tentative'
ELSE 'GRANT'
END)
-- Return the result of the function
RETURN UPPER(@FamilyAccountReady)
END
Additionally, even after reading through multiple articles online I am unable to find how the computer column is triggered. Is it triggered when any field on the record is updated? or is it only triggered when the variable fields are updated?
In this circumstance I am using the AccountID
and JunctionID
as variables and both are static fields that do not change. Will my computed column still work in this scenario?
As much as I dislike inefficiency, I may have to go with this design unless the expert community on here can suggest some improvement!
Many thanks in advance for your assistance!