插入不是主键的忽略重复项 [英] Insert into ignore duplicates that are not the primary key

查看:47
本文介绍了插入不是主键的忽略重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找一个SQL查询,该查询仅会插入值,但如果该值存在,则不会这样做.现在,我看过很多示例,但是它们都依赖于主键或表到表的移动.我只想在表中添加新行,并假设其中一个列不具有相同的值就将其添加.我知道以下内容将不起作用,但它与我想的差不多,并且如果我的文字不够用,可能会清除它.

I'm trying to find a query for sql that will just insert values but not do it should the value exist. Now ive seen alot of examples but they all rely on primary keys or table to table moves. I just want to add a new row in the table and assuming that one of the collumns doesnt have the same value add it. I know the following wont work but its as close to I think it would be and might just clear it up if my writting is not enough.

    INSERT INTO table (txtLastName,txtEmail,txtZip)
    Values ('Tester','test@test.com','12345')
    WHERE txtLastName <> 'Tester'
    or WHERE txtEmail <> 'test@test.com'
    or WHERE txtZip <> '12345'

使用MS SQL Server.

Using MS SQL Server.

推荐答案

您应该创建一个

You should create a Unique Constraint composed by the three fields (txtLastName, txtEmail, txtZip).

链接将您定向到SQL Server文档,但是唯一约束的概念是RDBMS通用的.

The links directs you to SQL Server docs, but the concept of unique constraint is RDBMS universal.

请注意,当您创建唯一约束时,重复的插入不仅会无声地失败:还会引发错误,指出插入试图违反唯一约束.而且,当然,它应该这样做!确保您的代码可以处理该异常.

Just beware that when you create a Unique Constraint, your duplicate insert will not just fail silently: it will throw an error saying the insert tried to violate the unique constraint. And, of course, it should do that! Make sure your code handles that exception.

这篇关于插入不是主键的忽略重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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