-1

我正在尝试编写一个 SQL 脚本来迁移一些数据。想象一下这种情况:

要迁移的表:

OLDTABLE
---------------
ID    VALUE     OLDVALUE
1     A         A
2     B         B

预期目标状态

NEWTABLE
---------------
ID    VALUE     NEWVALUE
1     A         Y
2     B         Z

到目前为止,我所拥有的是:

INSERT INTO NEWTABLE (ID, VALUE, NEWVALUE)
SELECT
    ID,
    VALUE,
    OLDVALUE
FROM OLDTABLE;

我的问题是如何OLDTABLE.OLDVALUE在插入之前修改从中选择的值NEWTABLE.NEWVALUE,以便每个 A 为 Y,每个 B 为 Z。

4

2 回答 2

1

Good old CASE expression:

INSERT INTO NEWTABLE (ID, VALUE, NEWVALUE)
SELECT
    ID,
    VALUE,
    CASE OLDVALUE
       WHEN 'A' THEN 'Y'
       WHEN 'B' THEN 'Z'
       ELSE OLDVALUE
    END
FROM OLDTABLE;

(I've assumed that if it's not A or B, it should be left unaltered)

于 2013-06-18T08:26:52.513 回答
1

Try this:

INSERT INTO NEWTABLE (ID, VALUE, NEWVALUE)
SELECT ID, VALUE,
  CASE WHEN OLDVALUE = 'A' THEN 'Y'
       WHEN OLDVALUE = 'B' THEN 'Z'
       ELSE 'NOT FOUND' -- handle NOT FOUND case here
  END AS NEWVALUE
FROM OLDTABLE
于 2013-06-18T08:27:09.513 回答