2009-10-20 39 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,它仍將返回所有行。 希望這可以幫助別人。

問候, 斯泰恩