ObjectDataSource和null参数

时间:2009-10-20 08:35:17

标签: asp.net objectdatasource coalesce vwdexpress

我正在使用Visual Web Developer 2008 EE使用数据集(.xsd)开发开发票应用程序,而我在创建自定义搜索查询时遇到问题。 我有一个ObjectDataSource需要4个ControlParameters,如下所示:

<asp:ObjectDataSource ID="odsInvoices" runat="server" SelectMethod="getInvoices" TypeName="bllInvoice">
    <SelectParameters>            
        <asp:ControlParameter ControlID="drpProjectsFilter" Type="Int32" Name="intProject" PropertyName="SelectedValue" ConvertEmptyStringToNull="True" />       
        <asp:ControlParameter ControlID="drpMonthsFilter" Type="Int32" Name="intMonth" PropertyName="SelectedValue" ConvertEmptyStringToNull="True" />
        <asp:ControlParameter ControlID="drpYearFilter" Type="Int32" Name="intYear" PropertyName="SelectedValue" ConvertEmptyStringToNull="True" />
        <asp:ControlParameter ControlID="drpStatusFilter" Type="Int32" Name="intStatus" PropertyName="SelectedValue" ConvertEmptyStringToNull="True" />
    </SelectParameters>

对于每个控件(下拉列表),我有一个默认值“”(=空字符串),我为每个参数添加了选项ConvertEmptyStringToNull =“True”。 ObjectDataSource后面的查询是这样的:

SELECT ... FROM ...
WHERE (YEAR(invoices.invoice_date) = COALESCE (@year, YEAR(invoices.invoice_date))) 
AND (invoices.fk_project_id = COALESCE (@projectID, invoices.fk_project_id)) 
AND (MONTH(invoices.invoice_date) = COALESCE (@month, MONTH(invoices.invoice_date))) 
AND (invoices.invoice_status = COALESCE (@statusID, invoices.invoice_status))

使用COALESCE,我基本上是要忽略4个参数中的任何一个,如果它们为null并返回所有行。

问题是这个查询不会返回任何行,除非我为4个参数中的每一个指定一个值,基本上是揭穿了这个自定义搜索的整个目的。

有关为什么这不起作用的任何想法? 提前致谢!

2 个答案:

答案 0 :(得分:1)

从MSSQL文档:

  

ISNULL和COALESCE虽然相同,但行为可能不同。涉及具有非空参数的ISNULL的表达式被认为是NOT NULL,而涉及具有非空参数的COALESCE的表达式被认为是NULL。

因此,请尝试将查询更改为:

select ...
  from ...
 where year(invoices.invoice_date)  = isnull(@year, year(invoices.invoice_date))
   and invoices.fk_project_id       = isnull(@projectID, invoices.fk_project_id)
   and month(invoices.invoice_date) = isnull(@month, month(invoices.invoice_date))
   and invoices.invoice_status      = isnull(@statusID, invoices.invoice_status)

如果这不起作用,请使用SQL事件探查器确切地检查调用它时{1}}传递给您的内容。

答案 1 :(得分:1)

我设法解决了自己的问题。 事实证明,ControlParameters没有返回NULL(如在dbnull值中),但实际数字为0.我已将SQL语句调整为以下内容:

select ...  from ... 
where ((@year=0) OR (year(invoices.invoice_date)=@year)) 
and ((@projectID=0) OR (invoices.fk_project_id=@projectID))   
and ((@month=0) OR (month(invoices.invoice_date)=@month))
and ((@statusID=0) OR (invoices.invoice_status=@statusID))

这样,如果ControlParameter的值为0,它仍将返回所有行。 希望这可以帮助别人。

此致 斯泰恩