如何避免 SQL 中 INSERT 的重复值? [英] How to avoid Duplicate values for INSERT in SQL?
本文介绍了如何避免 SQL 中 INSERT 的重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张表:
Delegates
这个表有四个字段:
ID(Auto increment, Primary)
MemberNo, FromYr, ToYr
我用这个查询插入:
INSERT INTO Delegates ([MemNo],[FromYr],[ToYr]) values(@MemNo, @FromYr,@ToYr)
值来自用户输入.一个成员可以成为任何一年的代表,这就是为什么我允许他们随意输入.但现在的问题是他们可以错误地插入同一年的一个成员超过 2 次.请帮我现在在这里做什么?
The values comes from user input. One member can be a Delegate for any year that's why I allow them to input as they want. But now problem is they can insert mistakenly one member for the same year more than 2 times. Please help me what can I do now here?
推荐答案
插入前检查是否有相同值的记录:
Before inserting check if there is a record with the same values:
if not exists (select * from Delegates d where d.FromYr = @FromYr and d.MemNo = @MemNo)
INSERT INTO Delegates ([MemNo],[FromYr],[ToYr]) values(@MemNo, @FromYr,@ToYr)
这篇关于如何避免 SQL 中 INSERT 的重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文