国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > 文庫 > 正文

多條件查詢的程序

2020-10-29 21:54:32
字體:
來源:轉載
供稿:網友
而在對用戶進行查詢時,也可能會使用到多種條件的查詢方式,如通過工號查詢、通過姓名查詢、通過性別查詢、通過學歷查詢等。也有可能會通過多種條件的組合查詢,如查學歷是大專的女員工等。
對于這種查詢情況,通常的作法是讓用戶輸入查詢條件,再進行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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 闽侯县| 咸宁市| 获嘉县| 金溪县| 涟源市| 临猗县| 德安县| 诸暨市| 康定县| 侯马市| 阳信县| 西林县| 阳江市| 保德县| 扎鲁特旗| 尼木县| 锦屏县| 承德市| 吕梁市| 聂拉木县| 嘉义县| 富平县| 专栏| 河间市| 台南县| 开封县| 长丰县| 习水县| 荥阳市| 克拉玛依市| 潞城市| 呈贡县| 日喀则市| 嘉荫县| 大姚县| 雷山县| 会昌县| 永康市| 建瓯市| 康保县| 独山县|