如何在Sql中的Where子句中设置If条件

时间:2012-06-06 06:51:32

标签: sql-server-2008

我想显示具有多个条件的条件,但是如果任何条件为null或者没有任何值而不是如何在where子句中设置。 例如:

where
SR.fk_Designation_ID = @pk_Designation_ID
and SR.fk_SeniorityCategory_ID = @pk_SeniorityCategory_ID
and SR.IsCurrent_Appointment = 1 and SR.fk_SeparationType_ID is null
order by Senority_Joining_For_Order,E.Date_Of_Birth

此处如果@pk_SeniorityCategory_IDnull,则我不希望在and SR.fk_SeniorityCategory_ID = @pk_SeniorityCategory_ID条款中包含where条件。

1 个答案:

答案 0 :(得分:2)

试试这个:

WHERE
SR.fk_Designation_ID = @pk_Designation_ID
AND (@pk_SeniorityCategory_ID IS NULL 
     OR 
     SR.fk_SeniorityCategory_ID = @pk_SeniorityCategory_ID)
AND SR.IsCurrent_Appointment = 1 AND SR.fk_SeparationType_ID IS NULL
ORDER BY Senority_Joining_For_Order,E.Date_Of_Birth