超经典的多条件查询

solution 1 the drawback is performance is slow

 

use testdb;
go
create proc dbo.usp_GetOrders
@OrderID as int=null,
@CustomerID as nchar(5)=null,
@EmployeeID as int=null,
@OrderDate as DateTime=null
with recompile
as
select OrderID,CustomerID,EmployeeID,OrderDate,filler
from dbo.orders
where (OrderID=@OrderID or @OrderID is null)
and (CustomerID=@CustomerID or @CustomerID is null)
and (EmployeeID=@EmployeeID or @EmployeeID is null)
and (OrderDate=@OrderDate or @OrderDate is null)
go

 

 

 

solution 2

--if you want this pro work well always,you must guarantee all column is not null
--when you use the coalesce function please place the input parameter as the first parameter
--drawback in performance too
ALTER PROC dbo.usp_GetOrders
@OrderID AS INT = NULL,
@CustomerID AS NCHAR(5) = NULL,
@EmployeeID AS INT = NULL,
@OrderDate AS DATETIME = NULL
WITH RECOMPILE
AS

SELECT OrderID, CustomerID, EmployeeID, OrderDate, filler
FROM dbo.Orders
WHERE OrderID = COALESCE(@OrderID, OrderID)
AND CustomerID = COALESCE(@CustomerID, CustomerID)
AND EmployeeID = COALESCE(@EmployeeID, EmployeeID)
AND OrderDate = COALESCE(@OrderDate, OrderDate);
GO

 

 

solution 3

--in 'case when' structure,must base on 'is not null' logic to around the limitation of all columns must not be null
--advantage :1 the column can be null 2good performance
alter PROC dbo.usp_GetOrders
@OrderID as int=null,
@CustomerID as nvarchar(5)=null,
@EmployeeID as int=null,
@OrderDate as datetime=null
as
declare @sql as nvarchar(4000);
set @sql=
N'select orderid,customerid,employeeid,orderdate,filler'
+N' from dbo.orders '
+N' where 1=1 '
+case when @OrderID is not null then N' and OrderID=@oid'
else N'' end
+case when @CustomerID is not null then N' and CustomerID=@cid '
else N'' end
+case when @EmployeeID is not null then N' and EmployeeID=@eid'
else N'' end
+case when @orderdate is not null then N' and OrderDate=@dt'
else N'' end;
exec sp_executesql
@sql,
N'@oid as int,@cid as nchar(5),@eid as int,@dt as datetime',
@oid=@OrderID,
@cid=@CustomerID,
@eid=@EmployeeID,
@dt=@OrderDate;
go

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值