Running SQL user defined function that returns boolean, in where clause

Chris Halcrow picture Chris Halcrow · May 31, 2013 · Viewed 42.5k times · Source

Hope this doesn't seem too simple. I've looked this up but I'm not so good at SQL user defined functions and their use so I'm not sure what's going on. Who fancies a few points for telling me why I'm getting the error:

An expression of non-boolean type specified in a context where a condition is expected, near ')'.

For this:

UPDATE LMI_Contact
SET Phone = NULL
WHERE dbo.LMI_IsSingleCharacterRepeated(Phone, '0')

where the function can be created using:

-- ***this will also find NULL and empty string values***
CREATE FUNCTION LMI_IsSingleCharacterRepeated (@string varchar(max), @char char(1))
RETURNS bit
AS 
BEGIN
    DECLARE @index int
    DECLARE @len int
    DECLARE @currentChar char(1)
    SET @index = 1
    SET @len= LEN(@string)

    WHILE @index <= @len
    BEGIN
        SET @currentChar = SUBSTRING(@string, @index, 1)
        IF @currentChar = @char
            SET @index= @index+ 1
        ELSE
            RETURN 0
    END
    RETURN 1
END;
GO

This function is for checking if a string is any specified single character, repeated. Hope someone finds it useful!

Answer

Thomas picture Thomas · May 31, 2013

You must use comparison operators against functions even if the return type is bit.

UPDATE LMI_Contact
SET Phone = NULL
WHERE dbo.LMI_IsSingleCharacterRepeated(Phone, '0') = 1