更新:修改下面的代码以允许范围(包括无界范围)
如果我理解正确,存储过程可以轻松处理诸如此类的查询。您可以通过检查来使参数可选NULL
。如果参数是NULL
,则不要根据它进行查询。
CREATE PROCEDURE schema.FindPayments
(
@MinPrice double = NULL,
@MaxPrice double = NULL,
@Currency char(3) = NULL,
@MinTranDate datetime = NULL,
@MaxTranDate datetime = NULL,
@TranStatus int = NULL
)
AS BEGIN
SELECT *
FROM Payments
WHERE (
@MinPrice IS NULL
OR TotalPrice >= @MinPrice
)
OR (
@MaxPrice IS NULL
OR TotalPrice <= @MaxPrice
)
OR (
@Currency IS NULL
OR Currency = @Currency
)
OR (
@MinTranDate IS NULL
OR TranDate >= @MinTranDate
)
OR (
@MaxTranDate IS NULL
OR TranDate <= @MaxTranDate
)
OR (
@TranStatus IS NULL
OR TranStatus = @TranStatus
)
END
您现在可以从传入的代码中DBNull.Value
为未指定的参数调用此存储过程,或者因为我已将NULL
所有参数指定为默认值,您可以只传递选定的参数。
SqlCommand l_findPayments = new SqlCommand("FindPayments", new SqlConnection("..."));
l_findPayments.CommandType = CommandType.StoredProcedure;
if ( l_totalPriceComparison == "Exact Amount" )
{
findPayments.Parameters.Add(new SqlParameter("@MinPrice", l_price));
findPayments.Parameters.Add(new SqlParameter("@MaxPrice", l_price));
}
else if ( l_totalPriceComparison == "Below Amount" )
findPayments.Parameters.Add(new SqlParameter("@MaxPrice", l_price));
else if ( l_totalPriceComparison == "Above Amount" )
findPayments.Parameters.Add(new SqlParameter("@MinPrice", l_price));
// "Any Price" will just leave the parameter
// blank, so it will not filter on price
// ... repeat for all params
SqlDataReader l_result = l_findPayments.ExecuteReader();