如何在sql中包含null作为搜索参数

时间:2014-03-09 06:54:31

标签: c# asp.net sql

TABLES:

tblEmployee - EmployeeId, EmployeeName    
tblActivity - EmployeeId, AppraisalId

AppraisalId的数据类型为int,其值为0-2NULL

2个下拉列表的选定值提供存储过程的参数。

用户可以搜索所有员工或任何员工的记录。同样,对于所有人,没有或任何一种类型的评估。

如果我只搜索AppraisalId为NULL的记录,该怎么办?否则查询工作正常。

ASPX:

<asp:dropdownlist id="ddlemployee" runat="server" appenddatabounditems="true">
 <asp:listitem text="--All--" value="0"/>
</asp:dropdownlist>

<asp:dropdownlist id="ddlappraisal" runat="server" appenddatabounditems="true">
 <asp:listitem text="--All--" value="-1"/> 
  <asp:listitem text="None"/>   //not sure what value this should have
  <asp:listitem text="Excellent" value="2"/>
  <asp:listitem text="Average" value="1"/>
  <asp:listitem text="Poor" value="0"/>
</asp:dropdownlist>

SQL:

alter procedure getdata
@EmployeeId int
@AppraisalId int
as
begin
 set nocount on;
 if  @EmployeeId = 0
 set @EmployeeId = null


 select e.employeename,a.appraisalid
 from tblemployee e
 left join tblactivity a on 
 ( e.employeeid = a.employeeid and 
   (e.employeeid = @Employeeid or @Employeeid is null) and
   (a.appraisalid = @AppraisalId or @AppraisalId = -1)       
 )
end

1 个答案:

答案 0 :(得分:1)

您可以为无选项提供-2的值:

<asp:listitem text="None" value="-2"/>

并修改查询(仅显示在此处选择,其余部分保持不变):

select e.employeename,a.appraisalid
 from tblemployee e
 left join tblactivity a on 
 e.employeeid = a.employeeid and 
   (e.employeeid = @Employeeid or @Employeeid is null) and
   (a.appraisalid = @AppraisalId or @AppraisalId = -1
       or (@AppraisalId = -2 and a.appraisalid is null)