多條件查詢的程式

來源:互聯網
上載者:User

而在對使用者進行查詢時,也可能會使用到多種條件的查詢方式,如通過工號查詢、通過姓名查詢、通過性別查詢、通過學曆查詢等。也有可能會通過多種條件的組合查詢,如查學曆是大專的女員工等。
對於這種查詢情況,通常的作法是讓使用者輸入查詢條件,再進行SQL語句組合來進行查詢。如讓使用者輸入工號、姓名等,單擊提交按鈕之後,在後台獲得這些資訊,如以下代碼所示:
複製代碼 代碼如下:
//設定查詢語句
string strSql = "SELECT * FROM [user] where UserState=1 ";
//如果使用者名稱不為空白則添加查詢條件
if (UserName!="")
{
    strSql += "and (UserName'= "+UserName+"') ";
}
//如果性別不為空白則添加查詢條件
if (Sex!="")
{
    strSql += "and (Sex'= "+Sex+"') ";
}

在建立完SQL語句之後,執行該語句獲得查詢結果。
這種是使用得最多並且是最不安全的方法,因為這是最容易讓別人SQL注入攻擊的一個方式。
如果想要避免SQL注入攻擊,可以將查詢語句寫在預存程序中,然後使用SqlParameter將參數傳遞給預存程序,但是,一個多條件查詢的預存程序需要怎麼寫呢?
其實,這個預存程序並不難,可以使用以下方式:
複製代碼 代碼如下:
CREATE PROCEDURE [dbo].[UserCheck]
@UserId varchar(50) = null,
@UserName varchar(20) = null,
@RealName varchar(20) = null,
@Sex bit = null,
@JobTitle varchar(50) = null,
@Organ varchar(50) = null,
@IDCardType smallint = null,
@IDCard varchar(50) = null,
@Mobile varchar(50) = null
AS
BEGIN
select * from [user]
where UserId like case when @UserId is null then UserId else @UserId end
and UserName like case when @UserName is null then UserName else @UserName end
and RealName like case when @RealName is null then RealName else @RealName end
and Sex = case when @Sex is null then Sex else @Sex end
and JobTitle like case when @JobTitle is null then JobTitle else @JobTitle end
and Organ like case when @Organ is null then Organ else @Organ end
and IDCardType = case when @IDCardType is null then IDCardType else @IDCardType end
and IDCard like case when @IDCard is null then IDCard else @IDCard end
and Mobile like case when @Mobile is null then Mobile else @Mobile end
END

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.