T-SQL SELECT logical operators in stored function not evaluating

22 views Asked by At

I have a table tblLineItem representing line items for a set of products. The columns are:

  • LineItemId int

  • ProductId int

  • IsActive bit

  • IsInventory bit

  • StockOnHand int

    LineItemId ProductId IsActive IsInventory StockOnHand
      8465        1281        True    True            0    
      8466        1281        True    True            0    
      18257       1281        True    True            0    
    

I have a scalar function to return a true/false bit if for a ProductId there are any non-inventory items or inventory items with StockOnHand <> 0

ALTER FUNCTION [dbo].[ProductIsInStock]
(
    @ProductId bit
)
RETURNS bit
AS
BEGIN
    DECLARE @True bit = 1
    DECLARE @False bit = 0
    DECLARE @IsInStock bit = @False

    IF EXISTS (SELECT TOP (1) LineItemId
            FROM tblLineItem
            WHERE tblLineItem.ProductId = @ProductId
                AND tblLineItem.IsActive = @True
                AND (IsInventory = @False OR tblLineItem.StockOnHand <> 0)
        )
    BEGIN
            SET @IsInStock = @True
        END

    -- Return the result of the function
    RETURN @IsInStock
END

Works correctly if a ProductId has at keast one IsInventory = @False (0) - it returns @True (1).

However, the function always returns @True (1) even if all records have IsInventory = @True(1) and tblLineItem.StockOnHand are zero (0).

A query on the above data: SELECT LineItemId, ProductId, IsActive, IsInventory, StockOnHand, dbo.ProductIsInStock(ProductId) AS InStock FROM tblLineItem WHERE (ProductId = 1281)

gives:

LineItemId ProductId IsActive IsInventory StockOnHand InStock
8465        1281        True    True            0       True
8466        1281        True    True            0       True
18257       1281        True    True            0       True

Yet a query in MSSMS in the same format yields the ciorrect result (no records returned):

SELECT TOP (1) LineItemId
FROM tblLineItem
WHERE tblLineItem.ProductId = 1281
    AND tblLineItem.IsActive = 1
    AND (tblLineItem.IsInventory = 0 OR tblLineItem.StockOnHand <> 0)

Am I missing something with the syntax in the logocial grouping of the (IsInventory = @False OR tblLineItem.StockOnHand <> 0) ?

Or is there something about the IF EXISTS which is always evaluating true?

Many thanks for any help, Peter.

0

There are 0 answers