数据库 
首页 > 数据库 > 浏览文章

多条件查询的程序

(编辑:jimmy 日期: 2024/9/17 浏览:3 次 )
而在对用户进行查询时,也可能会使用到多种条件的查询方式,如通过工号查询、通过姓名查询、通过性别查询、通过学历查询等。也有可能会通过多种条件的组合查询,如查学历是大专的女员工等。
对于这种查询情况,通常的作法是让用户输入查询条件,再进行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
上一篇:JDBC 数据库常用连接 链接字符串
下一篇:SQLServer与Access常用SQL函数区别
一句话新闻
一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?