Question

I have this SQL function which is wrapped by a stored procedure:

ALTER FUNCTION dbo.GetObjList
(
    @filterUID int = NULL,
    @filterSID varchar(32) = NULL
)
RETURNS TABLE
AS

RETURN 

SELECT ROW_NUMBER() OVER (ORDER BY UID) AS [RowNumber], * 
FROM ObjTable
WHERE 
    (COALESCE(@filterUID, @filterSID) IS NULL) OR 
    (
        ((@filterUID IS NOT NULL) AND (UID = @filterUID)) OR
        ((@filterSID IS NOT NULL) AND (SID = @filterSID))
    )

Why would I receive such an error: "Conversion failed when converting the varchar value 'abc' to data type int." if I pass only @filterSID = 'abc' as parameters (and DEFAULT for others) ?

I noticed that COALESCE is responsible for the error.

EDIT: Now that I got the reason of the error... and given the fact that I have lots of params actually... what would you guys recommend as solution?

Was it helpful?

Solution

COALESCE:

Return Types

Returns the data type of expression with the highest data type precedence. If all expressions are nonnullable, the result is typed as nonnullable.

(Emphasis added). int had a higher precedence than varchar, so the return type of your COALESCE must be of type int. And obviously, your varchar value cannot be so converted.

You can re-write your where clause simply as:

WHERE 
    (@filterUID IS NULL AND @filterSID IS NULL) OR 
    (@filterUID IS NOT NULL AND UID = @filterUID) OR
    (@filterSID IS NOT NULL AND SID = @filterSID)

OTHER TIPS

Try converting the parameters in Coalesce to Varchar
For instance:

(COALESCE(CONVERT(VARCHAR,@filterUID), CONVERT(VARCHAR,@filterSID)) IS NULL) OR 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top