I have a function that I need to create that reads in the value of a column in a table and output a text value into a new column in the same table. The column in question (confidence_score) will have either a numeric value, a letter, or null value.
If confidence_score(nvarchar(2)) is a number and is less than or equal to 14, I need the computed column to have ‘High’ in it, otherwise ‘Low’. If confidence_score is not a number and has a value of ‘H’, I need the computed column to have ‘High’ in it, otherwise ‘Low’.
Here is the code I am using:
CREATE FUNCTION dbo.avm_confidence_level(@score nvarchar)
RETURNS nvarchar(5) as
BEGIN
DECLARE @conversion as nvarchar(5)
IF isnumeric(@score) = 1 BEGIN
IF cast(@score as int) <= 14 BEGIN
Set @conversion = 'High'
END
ELSE BEGIN
Set @conversion = 'Low'
END
END
ELSE BEGIN
IF @score = 'H' BEGIN
Set @conversion = 'High'
END
ELSE BEGIN
Set @conversion = 'Low'
END
END
RETURN @conversion
END
I am getting results using this code that are half right. The first check (isnumeric) seems to be working fine. I am getting High and Low values where I’m expecting them when the value is not a number. The issue seems to be within the isnumeric being true section. I am getting a value of ‘High’ regardless of what numeric value is actually in the confidence_score column. I’m not sure what I’m doing wrong here.
I appreciate any help anyone can offer.
Thank you.
It’s because you defined the function parameter as nvarchar instead of nvarchar(2). It’s truncating anything over one character, so all your ints above 9 are becoming 1. Try changing the definition to: