Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL, how do I allow for nulls in the parameter?

I have what seems to be a really easy SQL query I can't figure out and its driving me nuts. This is SQL 2008. Basically, there is a status field where the can pick "pending", "satisfied" or all. If they send in "pending" or "satisfied" there's no problem. But when they pick all I'm having problems. Mostly because I can't figure out how to get the records where this field is null to show up (because it has to be 'is null' instead of '= null'. (This is the way the data will come over; I have no control over that.)

The code I've been using does not work for nulls.

SELECT * FROM Payment_Table where Payment.Status_code = @status_id

like image 981
donde Avatar asked Feb 28 '23 18:02

donde


2 Answers

You can try

SELECT Col1, Col2,...,Coln --Required Columns
FROM Payment_Table 
where (Payment.Status_code = @status_id OR @status_id IS NULL)
like image 161
Adriaan Stander Avatar answered Mar 02 '23 13:03

Adriaan Stander


Try:

SELECT * 
FROM Payment_Table 
WHERE Payment.Status_code = ISNULL(@status_id, Status_code)

This will return all payments.

like image 28
Miyagi Coder Avatar answered Mar 02 '23 13:03

Miyagi Coder