SQL防止添加重复记录

时间:2019-02-01 16:53:22

标签: sql ms-access

我需要在此SQL语句中添加些什么,以说明是否在ProductionOrderNo中 SPECIALS_Output已经存在,是否不从TEMP_Specials添加记录? SPECIALS_Output中的ProductionOrderNo已经是主键。

strSqlAddTempSpecials = "INSERT INTO SPECIALS_Output ( ProductionOrderNo, ItemNo, Description, ExtraDescription, Quantity, ItemWeight, CreationDate, DueDate, StartingDate, Length ) " & _
"SELECT TEMP_Specials.ProductionOrderNo, TEMP_Specials.ItemNo, TEMP_Specials.Description, TEMP_Specials.ExtraDescription, TEMP_Specials.Quantity, TEMP_Specials.ItemWeight, TEMP_Specials.CreationDate, TEMP_Specials.DueDate, TEMP_Specials.StartingDate, LintelInfo.Length " & _
"FROM TEMP_Specials LEFT JOIN LintelInfo ON TEMP_Specials.ItemNo = LintelInfo.[No] " & _
"WHERE (((LintelInfo.ItemType)<>" & Chr(34) & "Brick" & Chr(34) & " And (LintelInfo.ItemType)<>" & Chr(34) & "#N/A" & Chr(34) & " And (LintelInfo.ItemType)<>" & Chr(34) & "Windpost Kit" & Chr(34) & ") AND ((TEMP_Specials.Status)=" & Chr(34) & "Finished" & Chr(34) & "));"

2 个答案:

答案 0 :(得分:0)

您可以在ProductionOrderNo

上创建唯一索引

在MS Access的设计视图中打开表,选择ProductionOrderNo,然后在属性(常规)下选择Indexed: yes (No Duplicates)

enter image description here

答案 1 :(得分:0)

一种解决方案是在查询中添加一个条件,以过滤目标表中已经存在的,属于ProductionOrderNo的记录。

这可以通过将LEFT JOIN与WHERE ... IS NULL结合使用,或在相关子查询上使用NOT EXISTS条件来实现。

这是LEFT JOIN的解决方案:

strSqlAddTempSpecials = 
    "INSERT INTO SPECIALS_Output ( ProductionOrderNo, ItemNo, Description, ExtraDescription, Quantity, ItemWeight, CreationDate, DueDate, StartingDate, Length ) " & _
"SELECT TEMP_Specials.ProductionOrderNo, TEMP_Specials.ItemNo, TEMP_Specials.Description, TEMP_Specials.ExtraDescription, TEMP_Specials.Quantity, TEMP_Specials.ItemWeight, TEMP_Specials.CreationDate, TEMP_Specials.DueDate, TEMP_Specials.StartingDate, LintelInfo.Length " & _
"FROM TEMP_Specials LEFT JOIN LintelInfo ON TEMP_Specials.ItemNo = LintelInfo.[No] " & _
"LEFT JOIN SPECIALS_Output ON SPECIALS_Output.ProductionOrderNo = TEMP_Specials.ProductionOrderNo " & _
"WHERE ((SPECIALS_Output.ProductionOrderNo IS NULL) AND ((LintelInfo.ItemType)<>" & Chr(34) & "Brick" & Chr(34) & " And (LintelInfo.ItemType)<>" & Chr(34) & "#N/A" & Chr(34) & " And (LintelInfo.ItemType)<>" & Chr(34) & "Windpost Kit" & Chr(34) & ") AND ((TEMP_Specials.Status)=" & Chr(34) & "Finished" & Chr(34) & "));"

这将在忽略重复项的同时插入新记录,这与独特的索引方法不同,唯一的索引方法会至少在重复项存在时立即拒绝所有记录。