欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

多條件查詢(xún)的程序

 更新時(shí)間:2009年05月27日 01:45:38   作者:  
在一個(gè)網(wǎng)站中,常常會(huì)使用到查詢(xún)功能。假設(shè)一個(gè)企業(yè)內(nèi)部網(wǎng)中,用戶(hù)信息里通常會(huì)涉及到工號(hào)、姓名、性別、學(xué)歷、職業(yè)、職稱(chēng)、身份證號(hào)碼、手機(jī)號(hào)碼、座機(jī)號(hào)碼、傳真號(hào)碼、郵政編號(hào)、通訊地址等信息。
而在對(duì)用戶(hù)進(jìn)行查詢(xún)時(shí),也可能會(huì)使用到多種條件的查詢(xún)方式,如通過(guò)工號(hào)查詢(xún)、通過(guò)姓名查詢(xún)、通過(guò)性別查詢(xún)、通過(guò)學(xué)歷查詢(xún)等。也有可能會(huì)通過(guò)多種條件的組合查詢(xún),如查學(xué)歷是大專(zhuān)的女員工等。
對(duì)于這種查詢(xún)情況,通常的作法是讓用戶(hù)輸入查詢(xún)條件,再進(jìn)行SQL語(yǔ)句組合來(lái)進(jìn)行查詢(xún)。如讓用戶(hù)輸入工號(hào)、姓名等,單擊提交按鈕之后,在后臺(tái)獲得這些信息,如以下代碼所示:
復(fù)制代碼 代碼如下:

//設(shè)置查詢(xún)語(yǔ)句
string strSql = "SELECT * FROM [user] where UserState=1 ";
//如果用戶(hù)名不為空則添加查詢(xún)條件
if (UserName!="")
{
    strSql += "and (UserName'= "+UserName+"') ";
}
//如果性別不為空則添加查詢(xún)條件
if (Sex!="")
{
    strSql += "and (Sex'= "+Sex+"') ";
}

在創(chuàng)建完SQL語(yǔ)句之后,執(zhí)行該語(yǔ)句獲得查詢(xún)結(jié)果。
這種是使用得最多并且是最不安全的方法,因?yàn)檫@是最容易讓別人SQL注入攻擊的一個(gè)方式。
如果想要避免SQL注入攻擊,可以將查詢(xún)語(yǔ)句寫(xiě)在存儲(chǔ)過(guò)程中,然后使用SqlParameter將參數(shù)傳遞給存儲(chǔ)過(guò)程,但是,一個(gè)多條件查詢(xún)的存儲(chǔ)過(guò)程需要怎么寫(xiě)呢?
其實(shí),這個(gè)存儲(chǔ)過(guò)程并不難,可以使用以下方式:
復(fù)制代碼 代碼如下:

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

相關(guān)文章

最新評(píng)論