简体   繁体   中英

Insert into table from select only when select returns valid rows

I want to insert into table from select statement but it is required that insert only happens when select returns valid rows. If no rows return from select, then no insertion happens.

insert into products (name, type) select 'product_name', type from prototype where id = 1

However, the above sql does insertion even when select returns no rows. It tries to insert NULL values.

I know the following sql can check if row exists

select exists (select true from prototype where id = 1)

How to write a single SQL to add the above condition to insert to exclude the case ?

You are inserting the wrong way. See the example below, that doesn't insert any row since none matches id = 1 :

create table products (
  name varchar(10),
  type varchar(10)
);

create table prototype (
  id int,
  name varchar(10),
  type varchar(10)
);

insert into prototype (id, name, type) values (5, 'product5', 'type5');  
insert into prototype (id, name, type) values (7, 'product7', 'type7');

insert into products (name, type) select name, type from prototype where id = 1
-- no rows were inserted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM