如果子查询返回null,则SQL查询失败

时间:2016-02-19 01:50:50

标签: sql postgresql subquery

如果下面的子查询没有找到任何记录,则返回null并将action_batch_id设置为如此。如果子查询没有返回记录,是否可以让整个查询失败/退出?

UPDATE action_batch_items 
SET action_batch_id = (SELECT id FROM action_batches WHERE id = '123' 
AND batch_count < 1000  AND batch_size < 100000) 
WHERE id = 1234567

更新:这是结构(它是ActiveRecord)

CREATE TABLE "public"."action_batches" (
    "id" int8 NOT NULL,
    "action_batch_container_id" int8 NOT NULL,
    "action_message" json,
    "adaptor" json,
    "batch_count" int4 DEFAULT 0,
    "batch_size" int8 DEFAULT 0
)

CREATE TABLE "public"."action_batch_items" (
    "id" int8 NOT NULL,
    "action_batch_id" int8,
    "config" json
)

2 个答案:

答案 0 :(得分:2)

create or replace function raise_error(text) returns int as $$
begin
  raise exception '%', $1;
  return -1;
end; $$ language plpgsql;

然后

action_batch_id = coalesce((select id ...), raise_error('No data'));

答案 1 :(得分:1)

尝试使用COALESCE()

UPDATE action_batch_items 
SET action_batch_id = 
(
    SELECT COALESCE(id, action_batch_id)
    FROM action_batches
    WHERE id = '123' AND batch_count < 1000  AND batch_size < 100000
) 
WHERE id = 1234567

如果子查询返回NULL,则不会更改action_batch_id列。如果子查询返回一个或多个非NULL条记录,则您的UPDATE将表现得像以前一样。