如果不存在SQL Server插入最佳实践[EXTENDED]

时间:2014-10-26 16:33:27

标签: mysql sql pdo mysqli

INSERT `locality` (province_id)
SELECT DISTINCT `province_id`
FROM `locality` localreturn
WHERE
   NOT EXISTS (SELECT * FROM `locality` local
              WHERE localreturn.province_id = local.province_id)

如果测试的查询通过了如何插入值?  正常的插入就像:

INSERT INTO `locality` (`province_id`) VALUES (1919)

Leeched来源: SQL Server insert if not exists best practice

1 个答案:

答案 0 :(得分:0)

尝试

  BEGIN
    IF NOT EXISTS(SELECT * FROM `locality` local WHERE  local.province_id=@id) 
    BEGIN
     INSERT `locality` (province_id) values(@id)
    END
  END