2013-04-09 37 views
1

我正在處理asp.net。我有一個SqlDataSource用硬編碼的SelectCommand上查詢:ASP.NET SqlDataSource,就像SelectCommand

<asp:SqlDataSource ID="DataSource1" runat="server" CancelSelectOnNullParameter="False" 
    ConnectionString="<%$ ConnectionStrings:S.Properties.Settings.ConnectionString %>" 
    SelectCommand="SELECT * FROM [table] 
    WHERE ([col1] like Case @col1_param When null Then col1 Else @col1_param End) 
    and ([col2] like Case @col2_param When null Then col2 Else @col2_param End)" 
    SelectCommandType="Text"> 
    <SelectParameters> 
     <asp:ControlParameter ControlID="TextBox1" Name="col1_param" PropertyName="Text" 
      Type="String" /> 
     <asp:ControlParameter ControlID="TextBox2" Name="col2_param" PropertyName="Text" 
      Type="String" /> 
    </SelectParameters> 

我想的是,如果你在一個文本框輸入數據而已,數據將只在WHERE子句的文本框的值根據顯示。如果兩個文本框均未放置任何值,則查詢將執行,就好像沒有任何位置一樣。

現在使用這段代碼,會發生什麼情況是,如果您只放在一個文本框中,則不顯示任何數據。如果所有文本框都是空白的,則相同。

我不想使用sql存儲過程。

我該如何解決這個問題?

謝謝...

回答

1

假設它傳遞空當沒有輸入文本,否則你將需要檢查空字符串

SelectCommand="SELECT * FROM [table] 
    WHERE ([col1] like '%@col1_param%' or @col1_param is null) 
    and ([col2] like '%@col2_param%' or @col2_param is null)" 
+0

謝謝!!!!!!!!!!! – trek 2013-04-09 04:31:24

0

這聽起來像你希望你的查詢可選搜索一列。

您可以使用格式

WHERE @col1_param IS NULL OR [col1] LIKE '%@col1_param%' 

財產處理情況未指定參數的情況下。

查看my question on the issue獲得完整答案。當然,它是作爲一個存儲過程完成的,但這個概念對於你的SQLDataSource將保持不變。

相關問題