SELECT ReceiptBatchID,
	ReferenceNumber, 
	BatchTotal AS Total, 
	RB.CreatedDate,
	KnownAs AS [User],
	(ReferenceNumber + ' ' + KnownAs + ' ' + System.Fn_ToYYYYMMDD(RB.CreatedDate)) AS Title
FROM App.ReceiptBatches AS RB
INNER JOIN Security.Users AS U ON RB.CreatedByID = U.UserID
WHERE IsCancelled = 0 AND 
(
CASE 
	WHEN ISNULL(@SearchText, '') <> '' THEN 
       CASE 
			WHEN System.Fn_ToYYYYMMDD(RB.CreatedDate) LIKE @SearchText + '%' THEN 1 
			WHEN ReferenceNumber LIKE '%' + @SearchText + '%' THEN 1 
			ELSE 0
		END
	ELSE 1
END
) = 1 AND 
(CASE WHEN ISNULL(@User, '') <> '' THEN 
       CASE WHEN KnownAs LIKE '%' + @User + '%' THEN 1 ELSE 0 END
       ELSE 1
END) = 1 AND 
(CASE WHEN ISNULL(@DateFrom, '') <> '' THEN 
       CASE WHEN RB.CreatedDate >= @DateFrom THEN 1 ELSE 0 END
       ELSE 1
END) = 1 AND 
(CASE WHEN ISNULL(@DateTo, '') <> '' THEN 
       CASE WHEN RB.CreatedDate <= @DateTo THEN 1 ELSE 0 END
       ELSE 1
END) = 1
ORDER BY ReferenceNumber ASC