SQL SERVER与MYSQL 的重复插入的区别

问题:
如果一条记录存在,不插入,如果不存在则插入
 
SQL SERVER 中:
create table b(id int)
insert into b select 1
union all
select 2
union all
select 3
union all
select 4

if not exists(select id from b where id=5)
insert into b(id) values(5)
===
MYSQL中没有简单的语句,只能用存储过程实现
 
MYSQL:
create table b(id int);
insert into b(id) values(1),(2),(3),(4);
 
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`sp_b`$$
CREATE PROCEDURE `test`.`sp_b`(in i_id int)
    BEGIN
    declare cnt int;
    select count(1) from b where id=i_id into cnt;
    if cnt = 0 then
       insert into b select i_id;
    end if;
    END$$
DELIMITER ;

本文出自 “上帝,咱们不见不散!” 博客,转载请与作者联系!

转载于:https://my.oschina.net/u/585111/blog/219444

猜你喜欢

转载自blog.csdn.net/weixin_33816611/article/details/92008326