sql – 在存储过程中选择all if参数为空

前端之家收集整理的这篇文章主要介绍了sql – 在存储过程中选择all if参数为空前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在sql Server中创建一个将选择并连接两个表的过程.参数@company,@from和@to始终设置,但@serie_type可以为NULL.如果@serie_type不为NULL,我只想包括指定的类型,简单AND S.Type = @serie_type,但如果@serie_type为NULL,我想包括所有类型,简单,只是不包括AND语句.我的问题是,我不知道如果@serie_type将被设置,因此我想要有这样的东西:
  1. /* pseudocode */
  2. ??? = AND (IF @serie_type IS NOT NULL S.Type = @serie_type)

这是一个简单的程序版本:

  1. CREATE PROCEDURE Report_CompanySerie
  2. @company INT,@serie_type INT,@from DATE,@to DATE
  3. AS
  4. BEGIN
  5. SELECT
  6. *
  7. FROM Company C
  8. JOIN Series S ON S.Company_FK = C.Id
  9. WHERE C.Id = @company
  10. AND S.Created >= @from
  11. AND S.Created <= @to
  12. /* HERE IS MY PROBLEM */
  13. AND ???
  14. END
  15. GO

不想复制选择,因为真正的选择是更大的这个.

解决方法

没有必要做AND(@serie_type IS NULL OR S.Type = @serie_type),因为sql Server有一个内置函数来为你做这个逻辑.

尝试这个:

  1. .
  2. .
  3. AND S.Type = isnull( @serie_type,S.Type)

这返回

如果@serie_type为空,则为true,否则为@serie_type = S.Type如果@serie_type为空,则为true.

MSDN

IsNull Replaces NULL with the specified replacement value.

06001

The value of check_expression is returned if it is not NULL; otherwise,replacement_value is returned after it is implicitly converted to the type of check_expression,if the types are different.

猜你在找的MsSQL相关文章