Well, I'm officially at a loss. I am trying to create a procedure that goes through each subsequent check and performs the corresponding request.
However, when I execute the procedure with one / two / all arguments, it always gets into the final ELSE and spits out the result set "all-all". WHY???
I suspect it could be: Syntax -If / Else -Use parentheses Keywords -Begin / End -Only IF conditions?
Any help is much appreciated!
Bonus points: can I optimize this with the search CASE in the WHERE clause? I know that I can really shave this code, but I am very curious why this does not work.
CREATE PROC spBalanceRange
@VendorVar varchar(50) = NULL,
@BalanceMax money = NULL,
@BalanceMin money = NULL
AS
IF
(
@VendorVar != NULL
AND @BalanceMin != NULL
AND @BalanceMax != NULL
)
BEGIN
SELECT VendorName, InvoiceNumber, InvoiceTotal - (PaymentTotal + CreditTotal) AS BalanceDue
FROM Invoices JOIN Vendors
ON Invoices.VendorID = Vendors.VendorID
WHERE
VendorName = @VendorVar
AND InvoiceTotal - (PaymentTotal + CreditTotal) >= @BalanceMin
AND InvoiceTotal - (PaymentTotal + CreditTotal) <= @BalanceMax
END
ELSE IF
(
@VendorVar != NULL
AND @BalanceMin = NULL
AND
(
@BalanceMax = NULL
OR @BalanceMax = 0
)
)
BEGIN
SELECT VendorName, InvoiceNumber, InvoiceTotal - (PaymentTotal + CreditTotal) AS BalanceDue
FROM Invoices JOIN Vendors
ON Invoices.VendorID = Vendors.VendorID
WHERE
VendorName = @VendorVar
AND InvoiceTotal - (PaymentTotal + CreditTotal) > 0
END
ELSE
BEGIN
SELECT VendorName, InvoiceNumber, InvoiceTotal - (PaymentTotal + CreditTotal) AS BalanceDue
FROM Invoices JOIN Vendors
ON Invoices.VendorID = Vendors.VendorID
WHERE
InvoiceTotal - (PaymentTotal + CreditTotal) > 0
END
;