Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Query 'Where' based on an If Statement

Hello I have following exert from a SQL server stored procedure:

SET @GenderToSearchBy =
        CASE 
            When @Gender IS NOT NULL And @Gender='M' THEN @MaleID
            When @Gender IS NOT NULL And @Gender='F' Then @FemaleID
            Else NULL
        End

SELECT FRST_NAME,LAST_NAME,ID_NUMB,GRDE_DSCN,
GEND_ID FROM #TEMP_STUD WHERE GEND_ID=@GenderToSearchBy

Now, I want this to work that if @Gender is NULL or not equal to M or F then search both genders, meaning that WHERE isn't required, is there any way to do that without writing 2 separate queries inside a CASE?

like image 991
Art F Avatar asked Sep 08 '26 06:09

Art F


1 Answers

try using COALESCE

WHERE GEND_ID = COALESCE(@GenderToSearchBy, GEND_ID)

or ISNULL

WHERE GEND_ID = ISNULL(@GenderToSearchBy, GEND_ID)
  • COALESCE()
  • ISNULL()
like image 148
John Woo Avatar answered Sep 10 '26 17:09

John Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!