我想在sql Server中创建一个将选择并连接两个表的过程.参数@company,@from和@to始终设置,但@serie_type可以为NULL.如果@serie_type不为NULL,我只想包括指定的类型,简单AND S.Type = @serie_type,但如果@serie_type为NULL,我想包括所有类型,简单,只是不包括AND语句.我的问题是,我不知道如果@serie_type将被设置,因此我想要有这样的东西:
- /* pseudocode */
- ??? = AND (IF @serie_type IS NOT NULL S.Type = @serie_type)
这是一个简单的程序版本:
- CREATE PROCEDURE Report_CompanySerie
- @company INT,@serie_type INT,@from DATE,@to DATE
- AS
- BEGIN
- SELECT
- *
- FROM Company C
- JOIN Series S ON S.Company_FK = C.Id
- WHERE C.Id = @company
- AND S.Created >= @from
- AND S.Created <= @to
- /* HERE IS MY PROBLEM */
- AND ???
- END
- GO
不想复制选择,因为真正的选择是更大的这个.
解决方法
没有必要做AND(@serie_type IS NULL OR S.Type = @serie_type),因为sql Server有一个内置函数来为你做这个逻辑.
尝试这个:
- .
- .
- 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.