這篇文章主要講解了“如何實現多條件查詢”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“如何實現多條件查詢”吧!
而在對用戶進行查詢時,也可能會使用到多種條件的查詢方式,如通過工號查詢、通過姓名查詢、通過性別查詢、通過學歷查詢等。也有可能會通過多種條件的組合查詢,如查學歷是大專的女員工等。
對于這種查詢情況,通常的作法是讓用戶輸入查詢條件,再進行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
感謝各位的閱讀,以上就是“如何實現多條件查詢”的內容了,經過本文的學習后,相信大家對如何實現多條件查詢這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。