带有SQL查询的复杂过滤条件



应用程序将5个不同的过滤条件从UI传递到查询。即--STORE CODE DESC NOTES QTY.

当我以不同的可能性添加这些条件时,它的时间很长,即

--1 0   0   0   0
IF @Store<>'0' AND @code='' AND @DESC='' AND @Notes='' AND @QTY=0 
--1 1   0   0   0
--1 1   0   0   1
--1 1   1   0   0
--1 1   1   1   0
etc..........

是否有任何方法可以简化它作为单个查询。希望这个问题是可以理解的。

我按照以下完成的示例代码,

SET @sql = 'Select * from tbl_store Where Inactive=0 ';
--10000
    IF @Store<>'0' AND @Code='' AND @Description='' AND @Notes='' --AND @Qty<>''
    SET @sql += ' AND Store=@Store  AND Quantity = @Qty';
    --11000
    ELSE IF @Store<>'0' AND @Code<>'' AND @Description='' AND @Notes='' --AND @Qty<>''
    SET @sql += ' AND Store=@Store  AND Code=@Code  AND Quantity = @Qty';

......................................................

我将在查询外放置任何验证,只需如下过滤您的查询。

SET @IsValidFilter=<YOUR VALIDATION LOGIC HERE>--IF YOU CAN'T TRUST INCOMING VALUES
SELECT
    *
FROM
    MyTable
WHERE
    (@IsValidFilter=1)
    AND 
    (@Store IS NULL OR MyTable.StoreID=@Store) 
    AND 
    (@code= IS NULL OR MyTable.CodeID=@Code)
    AND
    (@DESC IS NULL OR MyTable.Description=@Desc)
    AND
    (@Notes IS NULL OR MyTable.Notes=@Notes)

如果您不能信任要传递的值并根据参数值组合需要一些逻辑,那么创建一个@validfilter标志并只需添加最终的AND @ValidFilter=1即可在WHERE

一次做一个:

SET @sql = 'Select * from tbl_store Where Inactive = 0 ';
IF @Store <> '0' 
    SET @sql += ' and Store = @Store';
IF @Qty <> ''
    SET @sql += ' and Quantity = @Qty';
. . . .

出于表现原因,您正在做的是一个好主意。如果有适当的索引,则最终where子句应能够利用适当的索引。这样的单个where条件不会:

where (@store = '0' or start = @store) and
      (@qty = '' or quantity = @qty) and
      . . .
如果可能
select * 
from tbl_store ts
where ts.Inactive = 0
and (
    ( @Store <> '0' and @Description = '' and @Notes = '' and Store = @Store and Quantity = @Qty)
or
    (@Store <> '0' and @Code <> '' and @Notes <> '' and Code = @Code and Store = @Store and Quantity = @Qty)
);

使用动态查询(例如您的)可能会导致安全漏洞,以及对工作方式的一般混乱。我认为,这应该是最后一个度假胜地之一。

最新更新