Why BIT value Returned from a function doesn't work in IF statement

  • I created a simple function that checks a given string and return a value of BIT type.  The script of this function is attached.  
    When I was trying to use this function in following IF statement, I got error of "an expression of non-boolean type specified in a context where a condition is expected".  The function clearly returns a BIT value, which is considered as boolean.  Why the IF statement failed?
    -------------------------------------------------------------------------
    IF (dbo.fn_IsQueryFilter(@InParam))
        PRINT 'has input'
    ELSE
        PRINT 'no input value'
    -------------------------------------------------------------------------
    I also did another test with following script.  I got exact same error shown above.  When did I do wrong in these two scripts?  
    DECLARE @YN bit
    SELECT @YN = 1
    IF (@yn)
     PRINT 'is true'

  • You have to do it the long-winded way;

    If (condition) = 1
    Begin

    End

    The absence of evidence is not evidence of absence
    - Martin Rees
    The absence of consumable DDL, sample data and desired results is, however, evidence of the absence of my response
    - Phil Parkin

  • yyang4 - Sunday, January 20, 2019 10:00 AM

    I created a simple function that checks a given string and return a value of BIT type.  The script of this function is attached.  
    When I was trying to use this function in following IF statement, I got error of "an expression of non-boolean type specified in a context where a condition is expected".  The function clearly returns a BIT value, which is considered as boolean.  Why the IF statement failed?
    -------------------------------------------------------------------------
    IF (dbo.fn_IsQueryFilter(@InParam))
        PRINT 'has input'
    ELSE
        PRINT 'no input value'
    -------------------------------------------------------------------------
    I also did another test with following script.  I got exact same error shown above.  When did I do wrong in these two scripts?  
    DECLARE @YN bit
    SELECT @YN = 1
    IF (@yn)
     PRINT 'is true'

    There isn't a boolean data type in SQL Server and BIT is not boolean.  You need to specify the condition:

    IF dbo.fn_IsQueryFilter(@InParam) = 1
    PRINT 'true'
    ELSE
    PRINT 'false'

    Jeffrey Williams
    “We are all faced with a series of great opportunities brilliantly disguised as impossible situations.”

    ― Charles R. Swindoll

    How to post questions to get better answers faster
    Managing Transaction Logs

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply