2009-10-20 86 views
2

我正在使用Visual Web Developer 2008 EE使用数据集(.xsd)开发开发票应用程序,并且在创建自定义搜索查询时遇到问题。 我有预计4个ControlParameters,像这样一个ObjectDataSource:ObjectDataSource和null参数

<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 =”真“的每个参数。 是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个参数中的每一个指定了一个值,基本上揭穿了这个自定义搜索的整个目的。

任何想法,为什么这不工作? 在此先感谢!

回答

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事件探查器来检查被传递正是你SELECT当它被调用。

+0

谢谢伊恩,但我最初与ISNULL尝试这样做,也没有工作。另外,我想避免使用ISNULL,因为它仅在T-SQL中受支持,并且谁知道我们将来可能会更改我们的DB提供程序。 – 2009-10-20 09:40:51

+0

在这种情况下,我只能建议SQL Profiler :)。我在Mono中忽略了'ConvertEmptyStringToNull'被忽略的问题,但我怀疑它适用于你的情况。 – 2009-10-20 10:42:35

+0

看看我的答案SQL在http://stackoverflow.com/questions/1493458/search-based-on-matched-criteria/1493643#1493643我认为这将做你想做的事情,可能会更多一点便携。 – PhilPursglove 2009-10-20 14:20:35

1

我设法解决了我自己的问题。 事实证明,在ControlParameters没有返回NULL(如在DBNull的值),但实际数量为0。我已经适应我的SQL语句如下:

select ... from ... 
where ((@year=0) OR (year(invoices.invoice_date)[email protected])) 
and ((@projectID=0) OR ([email protected])) 
and ((@month=0) OR (month(invoices.invoice_date)[email protected])) 
and ((@statusID=0) OR ([email protected])) 

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

问候, 斯泰恩