缩短SQL条件

时间:2015-03-06 11:56:19

标签: sql sql-server-2008-r2

我有一些SQL条件,例如:

SELECT
  CASE WHEN RIGHT(CAST(COLUMN_A as nvarchar(max)),1) = '.' THEN
  SUBSTRING (COLUMN_A, DATALENGTH(COLUMN_A) - 4, 4) ELSE
  SUBSTRING (COLUMN_A, DATALENGTH(COLUMN_A) - 3, 4) END AS COL_1

在同一个选项中,我有其他人使用上面的规则检查,我必须重复所有。我正在寻找一种不重复其余代码的方法 像:

CASE
  WHEN COL_1 LIKE 'AAAA' OR
  COL_1 LIKE 'BBBB' OR
  COL_1 LIKE 'CCCC' OR
  COL_1 LIKE 'DDDD' THEN 1 ELSE 0 END AS Code

使用上面COL_1的结果进行其他检查。我怎样才能做到这一点?感谢。

4 个答案:

答案 0 :(得分:1)

您可以使用嵌套的SELECT命令:

SELECT CASE
  WHEN x.COL_1 LIKE 'AAAA' OR
  x.COL_1 LIKE 'BBBB' OR
  x.COL_1 LIKE 'CCCC' OR
  x.COL_1 LIKE 'DDDD' THEN 1 ELSE 0 END AS Code
FROM (
SELECT
  CASE WHEN RIGHT(CAST(COLUMN_A as nvarchar(max)),1) = '.' THEN
  SUBSTRING (COLUMN_A, DATALENGTH(COLUMN_A) - 4, 4) ELSE
  SUBSTRING (COLUMN_A, DATALENGTH(COLUMN_A) - 3, 4) END AS COL_1
) x

答案 1 :(得分:1)

SELECT *
FROM   (
        SELECT list_of_columns
             , CASE WHEN this=cool THEN 1 ELSE 0 END As computed_column
        FROM   ...
       ) As a_subquery
WHERE  computed_column = 1

答案 2 :(得分:1)

CASE语法应该是这样的:

CASE
  WHEN COL_1 LIKE 'AAAA' THEN 1 
  WHEN COL_1 LIKE 'BBBB' THEN 1 
  WHEN COL_1 LIKE 'CCCC' THEN 1 
  WHEN COL_1 LIKE 'DDDD' THEN 1 
ELSE 0 
END AS Code

答案 3 :(得分:1)

向内翻,即在子字符串中执行大小写:

SELECT
  SUBSTRING (COLUMN_A, DATALENGTH(COLUMN_A) -
    CASE WHEN RIGHT(CAST(COLUMN_A as nvarchar(max)),1) = '.' THEN then 4 else 3 end, 4) AS COL_1

并使用IN作为不同的值,如果需要验证长度(LIKE和尾随空白...)

CASE
  WHEN COL_1 IN ('AAAA','BBBB','CCCC','DDDD') and LENGTH(col_1) = 4 THEN 1
  ELSE 0 END AS Code