我的查詢有多個 if 條件,以便用戶可以根據下拉串列選擇從資料庫中搜索,例如,我想獲取是否擁有 pc 以及是否有筆記本電腦的用戶,
使用一個下拉串列,其中有 3 個選項,是和否。
一切正常,但我有一個排序問題,如下所示,我無法在查詢末尾添加(排序依據)的命令中的代碼中看到,因為如果我選擇了其中一個下拉選單,則會出現錯誤串列,
有什么想法在這種情況下如何使用 order by,
任何幫助將不勝感激。
<asp:DropDownList ID="DropDownList_pc" runat="server">
<asp:ListItem Text="all" Value="1"></asp:ListItem>
<asp:ListItem Text="yes" Value="2"></asp:ListItem>
<asp:ListItem Text="no" Value="3"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList_laptop" runat="server">
<asp:ListItem Text="all" Value="1"></asp:ListItem>
<asp:ListItem Text="yes" Value="2"></asp:ListItem>
<asp:ListItem Text="no" Value="3"></asp:ListItem>
</asp:DropDownList>
string command = "SELECT user_name, user_full_name from users_table where user_name > 0";
if (Int32.Parse(DropDownList_pc.SelectedItem.Value) == 2)
{
command = " and user_pc >= 1";
}
else if (Int32.Parse(DropDownList_pc.SelectedItem.Value) == 3)
{
command = " and user_pc = 0";
}
if (Int32.Parse(DropDownList_laptop.SelectedItem.Value) == 2)
{
command = " and user_laptop >= 1";
}
else if (Int32.Parse(DropDownList_laptop.SelectedItem.Value) == 3)
{
command = " and user_laptop = 0";
}
uj5u.com熱心網友回復:
怎么樣:
var pc = "";
if (DropDownList_pc.SelectedValue == "2")
pc = " and user_pc >= 1";
else if (DropDownList_pc.SelectedValue == "3")
pc = " and user_pc = 0";
var lap = "";
if (DropDownList_laptop.SelectedValue) == "2")
lap = " and user_laptop >= 1";
else if (DropDownList_laptop.SelectedValue) == "3")
lap = " and user_laptop = 0";
string command = $@"
SELECT user_name, user_full_name
FROM users_table
WHERE user_name > 0 {pc} {lap}
ORDER BY user_name";
它在概念上與 Serg 的建議完全相同,但是在我看來,將 SQL 構建在一起可以更清楚地看到它作為一個整體并對其進行擴展
我要說的一件事;注意不要以這種方式添加用戶提供的資料。可以檢查用戶提供的某些頁面值,并根據該值從硬編碼片段中以固定形式將 SQL 連接在一起,但不要試圖添加搜索 X 描述的 TextBox。
如果您確實想添加一個文本框,請將一個引數連接到您的 SQL 中:
var txt = "";
if(TextBox.Text != "")
txt = " and somecol LIKE @p1";
然后在構建命令時添加具有該名稱的引數和TextBox.Text作為引數值的引數...
if(TextBox.Text != "")
command.Parameters.Add(new SqlParameter("@p1", SqlDbType.Varchar, 100){ Value = TextBox.Text });
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/413617.html
標籤:
上一篇:列出訂購的尚未交付給會員的書籍
