多条件查询SQL,存储过程版,不用拼接SQL

本文介绍了一种使用存储过程和SQL参数来构建复杂查询的方法,这种方法可以有效防止SQL注入攻击,确保了应用程序的安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发中有很多查询时多条件的,通常的做法是,拼接字符串,但是这种做法很容易被黑客攻击,所以,保险点的做法是将参数同过SQLPARAMETE传递到存储过程中

 

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

转载于:https://www.cnblogs.com/jack-feng/archive/2011/01/24/1943259.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值