对于这种查询情况,通常的作法是让用户输入查询条件,再进行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
以上就是【多条件查询的程序】的全部内容了,欢迎留言评论进行交流!
© 版权声明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!邮箱:cxysz1@tom.com
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
8. 精力有限,不少源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别
丞旭猿论坛
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
8. 精力有限,不少源码未能详细测试(解密),不能分辨部分源码是病毒还是误报,所以没有进行任何修改,大家使用前请进行甄别
丞旭猿论坛
THE END
暂无评论内容