SQL - 在不存在的地方插入 [英] SQL - Insert Where Not Exists

查看:34
本文介绍了SQL - 在不存在的地方插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是一个完全微不足道的查询 - 如果不存在具有匹配 ID 的值,则将值插入表中:

I have what I thought to be a completely trivial query - insert values into a table if a value with a matching ID does not exist:

BEGIN
   INSERT INTO [dbo].[Contact_Categories](Contact_Category_ID, Description)
   VALUES (1, 'Internal')
   WHERE NOT EXISTS( SELECT * FROM [dbo].[Contact_Categories] WHERE Contact_Category_ID = 1)
END

我在 where 语句周围出现错误.为什么?我如何实现我的目标?

I get an error around the where statement. Why? How do I accomplish my goal?

推荐答案

您的问题来自 WHERE 对 UPDATE/SELECT 有效但 INSERT 不明白它的含义.

Your problem comes from WHERE being valid for UPDATE/SELECT but INSERT just doesn’t understand what it means.

但是你可以解决这个问题.将您的代码更改为:

But you can get around this. Change your code to be like:

BEGIN
   INSERT INTO [dbo].[Contact_Categories](Contact_Category_ID, Description)
   SELECT 1, 'Internal'
   WHERE NOT EXISTS( SELECT * FROM [dbo].[Contact_Categories] WHERE Contact_Category_ID = 1)
END

这篇关于SQL - 在不存在的地方插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆