SQL“和/或” - 哪个订单?

时间:2017-07-14 00:48:45

标签: sql sql-server-2008

我有两个变量,我试图在where子句中传递。

where (DeptValue = @DeptValue and AccValue = @AccValue) or (DeptValue = @DeptValue )

以上似乎不起作用。我试图得到结果,如果我只是传递@Deptvalue然后所有部门与任何Acct记录返回。但如果出现@DeptValue和@AcctValue,则只返回带有Acct的部门。

任何帮助表示赞赏。感谢

2 个答案:

答案 0 :(得分:4)

您可以先检查DeptValue,然后检查AccValue是否存在。

  where (DeptValue = @DeptValue) and (@AccValue is null or AccValue = @AccValue)

答案 1 :(得分:0)

Operator precedence

Level   Operators
1       ~ (Bitwise NOT)
2       * (Multiply), / (Division), % (Modulo)
3       + (Positive), - (Negative), + (Add), (+ Concatenate), - (Subtract), & (Bitwise AND), ^ (Bitwise Exclusive OR), | (Bitwise OR)
4       =, >, <, >=, <=, <>, !=, !>, !< (Comparison operators)
5       NOT
6       AND
7       ALL, ANY, BETWEEN, IN, LIKE, OR, SOME
8       = (Assignment)

但是,通常认为使用括号来表达订单操作而不是依赖优先级是最佳做法。