我有一个总是有0或1行的表。我想编写一个脚本,如果它是空的,将插入一行,如果有一行则不执行任何操作。我试过这个:
SELECT * CASE WHEN (SELECT COUNT(*) FROM table < 0)
THEN (INSERT INTO table (a, b, c, d) VALUES ('a', 'b', 'c', 'd'))
END CASE
FROM table;
但我明白了:
在预期的地方找不到FROM关键字。
这看起来应该很简单我做错了什么?
答案 0 :(得分:13)
您可以将查询重组为select / insert,并使用not exists
关键字检查表是否为空,如下所示:
insert table (a, b, c, d)
select 'a', 'b', 'c', 'd'
from dual
where not exists (select 1 from table)
或者,如果它需要是if
语句,同样地:
if not exists (select 1 from table)
insert table (a, b, c, d) values ('a', 'b', 'c', 'd')
答案 1 :(得分:0)
将MERGE语句与INSERT但不使用UPDATE
一起使用