我正在尝试编写一个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
之前修改从{{1}}中选择的值,以便每个B的每个A和Z都为Y.
答案 0 :(得分:1)
INSERT INTO NEWTABLE (ID, VALUE, NEWVALUE)
SELECT
ID,
VALUE,
CASE OLDVALUE
WHEN 'A' THEN 'Y'
WHEN 'B' THEN 'Z'
ELSE OLDVALUE
END
FROM OLDTABLE;
(我假设如果它不是A
或B
,则应该保持不变)
答案 1 :(得分:1)
试试这个:
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