简体   繁体   English

在sql case语句中使用比较符号

[英]Use comparison signs inside a sql case statement

I'm looking for a way to build case statements in a sql select query using less than and greater than signs. 我正在寻找一种使用小于和大于符号在sql select查询中构建case语句的方法。 For example, I want to select a ranking based on a variable: 例如,我想根据变量选择排名:

DECLARE @a INT
SET @a = 0

SELECT CASE 
         WHEN @a < 3 THEN 0
         WHEN @a = 3 THEN 1
         WHEN @a > 3 THEN 2
       END

I'd like to write it as: 我想把它写成:

DECLARE @a INT
SET @a = 0

SELECT CASE @a
         WHEN < 3 THEN 0
         WHEN 3 THEN 1
         WHEN > 3 THEN 2
       END

...but SQL doesn't let me use the < and > signs in this way. ...但SQL不允许我以这种方式使用<和>符号。 Is there a way that I can do this is SQL 2005, or do I need to use the code like in the first one. 有没有办法可以做到这一点是SQL 2005,还是我需要像第一个那样使用代码。

The reason for only wanting the code there once is because it would make the code a lot more readable/maintainable and also because I'm not sure if SQL server will have to run the calculation for each CASE statement. 只需要一次代码的原因是因为它会使代码更易读/可维护,而且因为我不确定SQL服务器是否必须为每个CASE语句运行计算。

I'm looking for a VB.NET case statement equivelent: 我正在寻找一个VB.NET案例声明equivelent:

Select Case i
    Case Is < 100
        p = 1
    Case Is >= 100
        p = 2
End Select

Maybe it's not possible in SQL and that's ok, I just want to confirm that. 也许这在SQL中是不可能的,没关系,我只想确认一下。

You can use the SIGN function as 您可以使用SIGN功能

DECLARE @a INT
SET @a = 0

SELECT CASE SIGN(@a - 3)
         WHEN -1 THEN 0
         WHEN 0 THEN 1
         WHEN 1 THEN 2
       END

If @a is smaller than 3, then @a - 3 results in a negative int, in which SIGN returns -1. 如果@a小于3,则@a - 3导致负int,其中SIGN返回-1。

If @a is 3 or greater, then SIGN returns 0 or 1, respectively. 如果@a为3或更大,则SIGN分别返回0或1。


If the output you want is 0, 1 and 2, then you can simplify even more: 如果您想要的输出是0,1和2,那么您可以进一步简化:

DECLARE @a INT
SET @a = 0

SELECT SIGN(@a - 3) + 1

Using SIGN as suggested by @Jose Rui Santos seems a nice workaround. 使用@Jose Rui Santos建议的 SIGN似乎是一个很好的解决方法。 An alternative could be to assign the expression an alias, use a subselect and test the expression (using its alias) in the outer select: 另一种方法是为表达式分配别名,使用子选择并在外部选择中测试表达式(使用其别名):

SELECT
  …,
  CASE
    WHEN expr < 3 THEN …
    WHEN expr > 3 THEN …
  END AS …
FROM (
  SELECT
    …,
    a complex expression AS expr
  FROM …
  …
)
SELECT 
CASE 
WHEN ColumnName >=1 and ColumnName <=1 THEN 'Fail'
WHEN ColumnName >=6 THEN 'Pass'
ELSE 'Test'
END
FROM TableName

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

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