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是为了当查询条件都不需要用到时就查询全部数据

原文地址:https://www.cnblogs.com/xyyt/p/3214841.html