In a SQL Server 2022 database (compatibility level 160), I get this error when executing a scalar function:
Msg 245, Level 16, State 1, Line 22
Conversion failed when converting the varchar value 'PA' to data type int.
Code:
ALTER FUNCTION [dbo].[fnContractContainFlag]
(@iContractNo int,
@FlagCode as char(10))
RETURNS BIT
AS
BEGIN
DECLARE @bResult bit = 0,
@cPattern CHAR(3) = '%,%'
IF PATINDEX(@cPattern, RTRIM(@FlagCode)) > 0
BEGIN
IF EXISTS (SELECT tfl.pkTitleFlagID
FROM dbo.TitleFlag tfl
INNER JOIN dbo.Title ttl ON (ttl.TitleID = tfl.TitleID)
INNER JOIN dbo.Flag flg ON (flg.FlagID = tfl.FlagID)
INNER JOIN dbo.fnSplit(RTRIM(@FlagCode), ',') tmp ON (tmp.VALOR = flg.pkFlagID)
WHERE ttl.ContractNo = @iContractNo
BEGIN
SET @bResult = 1
END
ELSE
BEGIN
SET @bResult = 0
END
END
ELSE
BEGIN
IF (EXISTS (SELECT f.FlagCode
FROM Title t
INNER JOIN TitleFlag tf ON (tf.TitleID = t.TitleID)
INNER JOIN Flag f ON (f.FlagID = tf.FlagID)
WHERE t.ContractNo = @iContractNo
AND RTRIM(f.FlagCode) = RTRIM(@FlagCode)))
BEGIN
SET @bResult = 1
END
ELSE
BEGIN
SET @bResult = 0
END
END
RETURN (@bResult)
end
Note: dbo.fnSplit
is a table-valued function.
When I ran the function
select dbo.fnContractContainFlag(308668,'PA')
runs fine.
When I ran
select dbo.fnContractContainFlag(318668, 'PA')
I get that error Msg 245...
Why the strange behaviour even when passing the same pattern in the parameter values?
What's wrong in my code?
If set INLINE = OFF in the function, the problem not show any more.
Regards.
In SQL Server 2012 the code described runs like a charm.