当前位置: 移动技术网 > IT编程>数据库>其他数据库 > 多条件查询的程序

多条件查询的程序

2017年12月08日  | 移动技术网IT编程  | 我要评论
而在对用户进行查询时,也可能会使用到多种条件的查询方式,如通过工号查询、通过姓名查询、通过性别查询、通过学历查询等。也有可能会通过多种条件的组合查询,如查学历是大专的女员工
而在对用户进行查询时,也可能会使用到多种条件的查询方式,如通过工号查询、通过姓名查询、通过性别查询、通过学历查询等。也有可能会通过多种条件的组合查询,如查学历是大专的女员工等。
对于这种查询情况,通常的作法是让用户输入查询条件,再进行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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网