SQL Server多条件查询的实现

SQL Server多条件查询的实现

SQL Server多条件查询我们经常会用到,下面就教您如何使用存储过程实现SQL Server多条件查询,希望对您学习SQL Server多条件查询方面有所帮助。

以前使用的方法是将所有参数进行判断,然后对不同情况组合对应的sql查询语句,以实现分页和查询,但这种方法只适合查询条件较少的情况,如果查询条件过多那就恐怖了,比如四个条件查询,那就有4*4=16中可能要判断,可想而知,要用多少代码,辛苦多少脑细胞来写完这个判断语句,呵呵。

直到遇到了多达10个查询条件的查询事件,这种方法就彻底被我否决了。带着这种需求,找到了一种简便又很清晰的方法,

复制代码
/*查询资讯类别列表*/
IF EXISTS (SELECT name FROM sysobjects 
         WHERE name = 'get_list_newscate' AND type = 'P')
   DROP PROCEDURE get_list_newscate
GO
create proc get_list_newscate
@newscate_pid int,
@newscate_depth int,
@newscate_language int
as
select * from [news category] where 1=1
and (@newscate_pid is null or newscate_pid=@newscate_pid)
and (@newscate_depth is null or newscate_depth=@newscate_depth)
and (@newscate_language is null or newscate_language=@newscate_language)
order by newscate_orderid
复制代码

此存储过程可以实现SQL Server多条件查询,可以用于网站高级检索的功能

查询条件默认为null
程序中值类型不能为null可以在类型后加一个?这样就可以null
比如:int i=null 错误 int? i=null正确

where 1=1是为了当查询条件都不需要用到时就查询全部数据

posted on   逍遥云天  阅读(5225)  评论(0编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示