UPDATE:修改下面的代码,以允许范围(包括无界范围)
一个存储过程可以很容易地处理的查询,如此,如果正确地明白。只需检查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
为默认为所有paramters,你可以通过选定的参数。
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();
来源
2013-06-21 17:38:37
JDB
只有当用户选择“确切金额”,“确切日期”和除“任何状态”以外的任何状态时,这才起作用。例如,如果用户选择“低于金额”,则将无法返回准确的结果。 – HardCode
@HardCode - 你是对的。一个简单的修改将允许你指定范围。一个确切的值'N'只会在'N到N'的范围内。对于像“任何状态”这样的东西,您只需将参数留空即可(因此返回任何状态)。 – JDB