How can we handle empty ControlParameter values in SQL CONTAINS()
condition without using code-behind (so that it returns all results)? Looking probably for something like LIKE '%'
or WHERE (1=1)
.
<asp:TextBox ID="tbSearch" runat="server" placeholder="Search" ></asp:TextBox>
<asp:SqlDataSource ID="SqlDataSourceA" runat="server" ConnectionString="..."
SelectCommand="SELECT [Columns] FROM [Table]
WHERE CONTAINS([Column],@searchText) ORDER BY [Time] DESC">
<SelectParameters>
<asp:ControlParameter Name="searchText" ControlID="tbSearch"
PropertyName="Text" DefaultValue="?" />
</SelectParameters>
</asp:SqlDataSource>
I know that one way is to create a dynamic query in code behind, but maybe there's other way to do that with just markup.
EDIT: ControlParameter default value is empty string.
看看mssql的IS NULL属性
Make the WHERE
something like WHERE CONTAINS([Column], COALESCE(@searchText, [Column]))
Basically the idea is that if @searchText
is null, use [Column]
, and [Column]
contains [Column]
so everything should be returned.
Might have issues if @searchText
isn't null but just blank, you'd have use a CASE
statement to check for length or something similar.
For empty string handling, I couldn't get the 2nd param of CONTAINS to accept a case statement, so this should work: WHERE [COLUMN] = CASE WHEN LEN(RTRIM(LTRIM(COALESCE(@searchText, '')))) = 0 THEN [COLUMN] ELSE @searchText END
Obviously you can then change the '=' to LIKE
if needed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.