sybase中的case语句

时间:2016-10-08 02:37:13

标签: sql sybase case-statement

我对Sybase Query有以下要求: -

如果出现以下情况,请排除在下方:

  • SSN有多于或少于九位
  • SSN包​​含非数字字符
  • SSN为空白
  • SSN包​​含相同的数字(例如,000000000,1111111111或999999999)
  • SSN的第一个数字为9,第四个数字为7,8或9
  • 第四和第五位数字是00(800-00-0000除外)
  • 第六至第九位数字是0000

我写的案例陈述如下,但它不起作用,有人可以帮忙吗:

SELECT CASE
    WHEN LEN(a.MEMBER_SSN) > 9 THEN ' '
    WHEN LEN(a.MEMBER_SSN) < 9 THEN ' '
    WHEN LTRIM(RTRIM(a.MEMBER_SSN)) like '%[A-Z,a-z]%' then ' '
    WHEN LTRIM(RTRIM(WHEN a.MEMBER_SSN)) like '%[0-9]%' then ' '
    WHEN LTRIM(RTRIM(a.MEMBER_SSN)) in ( '000000000','000000001','000000002','000000003','000000004','000000005','999999999','111111111','000000070','123456789','999999998','000000071','888888888', ) THEN ''
    WHEN LTRIM(RTRIM(a.MEMBER_SSN)) NOT LIKE '9__[789]%' THEN a.MEMBER_SSN ELSE ' '
    WHEN LTRIM(RTRIM(a.MEMBER_SSN)) NOT LIKE '____[00]%' THEN a.MEMBER_SSN ELSE ' '
    WHEN LTRIM(RTRIM(a.MEMBER_SSN)) NOT LIKE '_____[0000]%' THEN a.MEMBER_SSN ELSE ' '
    END AS SUBSCRIBER_SSN From dbo.MEMBER_TABLE a

2 个答案:

答案 0 :(得分:0)

这是一个较短的版本:

SELECT (CASE WHEN LEN(a.MEMBER_SSN) <> 9 THEN ' '
             WHEN a.MEMBER_SSN LIKE '%[^0-9]%' THEN ' '
             WHEN REPLACE(a.MEMBER_SSN, LEFT(a.MEMBER_SSN, 1), '') = '' THEN ' '
             WHEN a.MEMBER_SSN LIKE '9__[789]%' THEN ' '
             WHEN a.MEMBER_SSN LIKE '___00%' AND a.MEMBER_SSN <> '800-00-0000' THEN ' '
             WHEN a.MEMBER_SSN LIKE '%0000' THEN ' '
             ELSE a.MEMBER_SSN
        END) AS SUBSCRIBER_SSN
From dbo.MEMBER_TABLE a

这几乎是你病情的直接转录。

答案 1 :(得分:0)

第一个问题是语法错误。每个ELSE只能有一个CASE

CASE
  WHEN ... THEN ...
  WHEN ... THEN ...
  WHEN ... THEN ... ELSE ... -- this ELSE doesn't belong here
  WHEN ... THEN ... ELSE ... -- and this ELSE should go to the next line for readability
END      

然后,您想在不满足任何拒绝条件(NOT ... AND NOT ...)时选择 SSN,但是

WHEN LTRIM(RTRIM(a.MEMBER_SSN)) NOT LIKE '9__[789]%' THEN a.MEMBER_SSN

无论以下条件如何,都会选择 SSN。

这是如何使用 ANDOR 编写条件的一种选择:

WHEN TRIM(a.member_ssn) = '800000000'
OR
(
  TRIM(a.member_ssn) LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
  AND
  TRIM(a.member_ssn) NOT LIKE '___00%'
  AND
  TRIM(a.member_ssn) NOT LIKE '%0000'
  AND
  TRIM(a.member_ssn) NOT LIKE '9__[789]%'
  AND
  TRIM(a.member_ssn) NOT IN ('000000000', '111111111', ... '999999999')
) THEN TRIM(a.member_ssn)
  ELSE ' '
END AS subscriber_ssn