它告诉我这里有一个错误:
if not exists (select * from ARCUS where CUSTOMER_NO = a)
begin
insert into ARCUS (CUSTOMER_NO) values (a)
end
答案 0 :(得分:2)
@Barmar有很好的解决方案,但我无法+1答案...
只需在“ CUSTOMER_NO”上添加唯一键
使用mysql时,还应使用小写形式写出字段和tbl名称。
ALTER TABLE `ARCUS` ADD UNIQUE INDEX `UNIQUE_CUSTOMER_NO` (`CUSTOMER_NO`);
然后做
INSERT IGNORE INTO `ARCUS` SET `CUSTOMER_NO` = 'a'
答案 1 :(得分:0)
假设此代码在存储过程中,则在INSERT
查询之后您会丢失分号。
if not exists (select * from ARCUS where CUSTOMER_NO = a)
begin
insert into ARCUS (CUSTOMER_NO) values (a);
end
但是,如果CUSTOMER_NO
是表中的唯一键,则可以通过单个查询来完成:
insert ignore into ARCUS (CUSTOMER_NO) values (a);
其优点是不必在过程中。
答案 2 :(得分:0)
此外,作为变体,您可以执行以下操作:
insert into ARCUS (CUSTOMER_NO)
select 'a'
where not exists (select 1 from ARCUS where CUSTOMER_NO = 'a');