简体   繁体   English

SQL Server 2000存储过程带有参数的分支

[英]SQL Server 2000 stored procedure branching with parameters

I want to create a stored procedure. 我想创建一个存储过程。 If the parameter is -1 then there should not be a where clause on that column else there should be a WHERE clause. 如果参数为-1,则该列上不应存在where子句,否则应存在WHERE子句。 What's the best way to do it without a lot of IF branching? 没有大量IF分支的最佳方法是什么?

I checked the archive. 我检查了档案。 There are a few similar questions but not exactly the same. 有一些类似的问题,但并不完全相同。

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

This works in many cases, (despite what the comments will say without trying it) because the optimiser will ignore the ISNULL bit. 这在很多情况下都可以使用(尽管注释会在不尝试的情况下显示),因为优化器将忽略ISNULL位。 Only works for non-null columns 仅适用于非空列

SELECT @site = NULLIF(@site, -1) ...

SELECT * from table  
  WHERE site = ISNULL(@site, site) ..

Otherwise, conditional WHERE which is usually bad because OR can not be optimised 否则,有条件的WHERE通常很糟糕,因为无法优化OR

SELECT * from table  
  WHERE (@site = -1 OR site = @site) AND  (...

Or separate stored procedures (don't think you want that either) 或单独的存储过程(也不要认为您想要的)

Or use sp_executesql (avoids dynamic SQL) 或使用sp_executesql(避免使用动态SQL)

How about: 怎么样:

SELECT * FROM table WHERE
  ((site = @site) OR (@site = -1)) AND
  ((promo = @promo) OR (@promo = -1)) AND
  ((type = @type) OR (@type = -1))

One caveat, though, you may find that SQL is not very intelligent in optimizing this sort of query. 需要注意的是,您可能会发现SQL在优化这种查询方面不是很聪明。

why fight against the obvious, simplest solution? 为什么要对抗显而易见,最简单的解决方案?

seriously, the branching solution make the intent clear, and can easily be understood by others. 认真地说,分支解决方案使意图很明确,并且很容易为他人所理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM