我想创建一个存储过程。如果参数为 -1,则该列上不应有 where 子句,否则应有 WHERE 子句。没有大量 IF 分支的最佳方法是什么?
我检查了文件。有几个类似的问题,但不完全相同。
CREATE PROCEDURE report
(
@site int,
@promo int,
@type int
)
AS
SET NOCOUNT ON
-- I want to avoid this:
IF @site = -1 AND @promo = -1 and @type = -1
BEGIN
SELECT * from table
END
IF @site > -1 AND @promo = -1 and @type = -1
BEGIN
SELECT * from table WHERE site = @site;
END
... -- other cases
ELSE -- all parameters are > -1
BEGIN
SELECT * from table
WHERE site = @site AND promo = @promo AND type = @type
END
最佳答案
这在很多情况下都有效(尽管注释会说没有尝试),因为优化器会忽略 ISNULL 位。仅适用于非空列
SELECT @site = NULLIF(@site, -1) ...
SELECT * from table
WHERE site = ISNULL(@site, site) ..
否则,条件 WHERE 通常很糟糕,因为 OR 无法优化
SELECT * from table
WHERE (@site = -1 OR site = @site) AND (...
或者单独的存储过程(也不认为您想要那样)
或者使用 sp_executesql(避免动态 SQL)
关于SQL Server 2000 带参数的存储过程分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1750883/