我想将插入/更新与case语句结合起来,这意味着我想在不存在的情况下插入行,如果有,则更新它,但在两种情况下都使用不同的值(更新时取决于id) )插入时,我设置好了......
这应该在一个SQL语句中发生: - )
简而言之:我试图将这两个陈述合并为一个:
1)。插入/更新:
MERGE INTO table_name USING dual ON (id='{id}')
WHEN MATCHED THEN UPDATE SET {col1}='{val1}', {col2}={val2}
WHEN NOT MATCHED THEN INSERT ({id}, {col1}, {col2}) VALUES ('{id}', '{val1}', {val2})
2)。使用大小写更新不同的值:
UPDATE SIGNALVALUE
SET
SIGNUMVALUE = CASE SIGID
WHEN 49634 THEN 1.1
WHEN 49674 THEN 2.2
WHEN 49675 THEN 1.8
END,
UPDATETIME = CASE SIGID
WHEN 49634 THEN TO_TIMESTAMP_TZ('2011-03-18 18:24:56:00', 'YYYY-MM-DD HH24:MI:SS:FF6 TZR')
WHEN 49674 THEN TO_TIMESTAMP_TZ('2011-03-18 18:24:56:00', 'YYYY-MM-DD HH24:MI:SS:FF6 TZR')
WHEN 49675 THEN TO_TIMESTAMP_TZ('2011-03-18 18:24:56:00', 'YYYY-MM-DD HH24:MI:SS:FF6 TZR')
END
WHERE SIGID IN (49634, 49674, 49675)
这些陈述只是一些例子。实际上还有更多的行要插入/更新,这种情况经常发生,所以我试图最小化查询量。
此外,我无法进行更新,然后查看受影响的行数,然后插入那些不存在的行,因为我不知道需要插入的行的ID与需要更新的行的ID。至少据我所知...请纠正我!
答案 0 :(得分:3)
它不必是using
子句中的表,也可以使用SQL查询
至少这是我认为你想要的:)
merge
into target_table
using (select case when ... then ... else ... end as id
from dual
) source_table
on(target_table.id = source_table.id)
when matched then
update
set ...
when not matched then
insert (...)
values (...)
如果有帮助,请告诉我。如果是这样,我也可以帮助编写最终查询。
答案 1 :(得分:0)
MERGE INTO SIGNALVALUE USING (
SELECT 49674 as SIGID,
TO_TIMESTAMP_TZ('2011-03-18 18:24:56:00', 'YYYY-MM-DD HH24:MI:SS:FF6 TZR') AS UPDATETIME,
'777' as SIGNUMVALUE
FROM dual
UNION ALL
SELECT 49675 as SIGID,
TO_TIMESTAMP_TZ('2011-03-18 18:24:56:00', 'YYYY-MM-DD HH24:MI:SS:FF6 TZR') AS UPDATETIME,
'777' as SIGNUMVALUE
FROM dual
UNION ALL
SELECT 49676 as SIGID,
TO_TIMESTAMP_TZ('2011-03-18 18:24:56:00', 'YYYY-MM-DD HH24:MI:SS:FF6 TZR') AS UPDATETIME,
'777' as SIGNUMVALUE
FROM dual
) n
ON(SIGNALVALUE.SIGID = n.SIGID)
WHEN NOT MATCHED THEN
INSERT (SIGID, SIGNUMVALUE, UPDATETIME) VALUES (n.SIGID, n.SIGNUMVALUE, n.UPDATETIME)
WHEN MATCHED THEN
UPDATE SET SIGNUMVALUE=n.SIGNUMVALUE, UPDATETIME=n.UPDATETIME