新列上的SQL长度,左,右

时间:2017-06-15 00:10:52

标签: sql

以下是代码(SQL的新增内容)。我需要修剪'Key_2并创建名为Project_Code的新列。我如何使用len并离开这个新列“Project_Code”。看起来代码只适用于原始列“Key_2”

 select 
    KEY_1,
    KEY_2,
    Replace (KEY_2, '&','') as Project_Code,
    FIELD_NAME,
    AUDIT_OLD_VALUE,
    AUDIT_NEW_VALUE

FROM TBADT_AUDIT_TRAIL 

Case
    If
    Len (Project_Code) <= 4
    then 
    Left (Project_Code, 4) as Proj_Code
    else
    Right (Project_Code, 2) as Proj_Phase

    End If

where Key_1 like 'WKSCHART'
and
Audit_Date between '2017-06-13' and '2017-06-14'

1 个答案:

答案 0 :(得分:0)

我认为这是你想要实现的目标 使用IIF,否则使用CASE,如果新Key2的长度超过4,则有一个项目阶段,否则只是一个项目代码?

SELECT
  KEY_1,
  KEY_2,
  IIF(LEN(REPLACE(KEY_2, '&', '')) <= 4, LEFT(REPLACE(KEY_2, '&', ''), 4), '') Project_code,
  IIF(LEN(REPLACE(KEY_2, '&', '')) > 4, RIGHT(REPLACE(KEY_2, '&', ''), 2), '') Project_Phase,
  FIELD_NAME,
  AUDIT_OLD_VALUE,
  AUDIT_NEW_VALUE
FROM TBADT_AUDIT_TRAIL
WHERE Key_1 LIKE 'WKSCHART'
AND Audit_Date BETWEEN '2017-06-13' AND '2017-06-14'

OR项目代码是左4,项目阶段是右2

SELECT
  KEY_1,
  KEY_2,
  LEFT(REPLACE(KEY_2, '&', ''), 4) Project_code,
  RIGHT(REPLACE(KEY_2, '&', ''), 2) Project_Phase,
  FIELD_NAME,
  AUDIT_OLD_VALUE,
  AUDIT_NEW_VALUE
FROM TBADT_AUDIT_TRAIL
WHERE Key_1 LIKE 'WKSCHART'
AND Audit_Date BETWEEN '2017-06-13' AND '2017-06-14'