2

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

<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 个参数中的任何一个(如果它们为空)并返回所有行。

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

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

4

2 回答 2

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 Profiler 准确检查SELECT调用时传递给您的内容。

于 2009-10-20T09:04:09.287 回答
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,它仍将返回所有行。希望这可以帮助某人。

问候, Stijn

于 2009-10-20T15:31:07.137 回答