T-SQL查询基于If语句的“Where”

时间:2013-04-12 18:02:23

标签: sql sql-server tsql stored-procedures

您好我从SQL服务器存储过程开始执行以下操作:

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

现在,我想要这样做,如果@Gender为NULL或不等于MF,则搜索两个性别,这意味着WHERE不是必需的,如果没有在CASE内编写2个单独的查询,有没有办法做到这一点?

1 个答案:

答案 0 :(得分:2)

尝试使用COALESCE

WHERE GEND_ID = COALESCE(@GenderToSearchBy, GEND_ID)

ISNULL

WHERE GEND_ID = ISNULL(@GenderToSearchBy, GEND_ID)