多条件查询的程序

 

    在一个网站中,常常会使用到查询功能。假设一个企业内部网中,用户信息里通常会涉及到工号、姓名、性别、学历、职业、职称、身份证号码、手机号码、座机号码、传真号码、邮政编号、通讯地址等信息。而在对用户进行查询时,也可能会使用到多种条件的查询方式,如通过工号查询、通过姓名查询、通过性别查询、通过学历查询等。也有可能会通过多种条件的组合查询,如查学历是大专的女员工等。

    对于这种查询情况,通常的作法是让用户输入查询条件,再进行SQL语句组合来进行查询。如让用户输入工号、姓名等,单击提交按钮之后,在后台获得这些信息,如以下代码所示:

 

    在创建完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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值