如何插入排除约束的记录

时间:2019-04-27 04:55:59

标签: sql-server tsql sql-server-2012

我在存储过程中有此查询:

INSERT INTO Checklist (AuditID, QType, Question, QNmbr, QID, ANmbr)  
    SELECT @AuditID, @QType, Question, displayorder AS QNmbr, id AS QID, 0 AS ANmbr 
    FROM Questions 
    WHERE Q_type = @QType

AuditID, QType, QNmbr, ANmbr上的清单表上有主键约束

在问题表中,对于Questions.Q_type中的少数$ awk '/^>/{f=/>k141_436839 /} f' file >k141_436839 flag=0 multi=1.0000 len=205 ATGAAATCACGATGTTTTTCTGATTCTACGAGTTAGGGAGAACATGAATCATCAGCTCTTTTTTAAATCTGGTGTTTGTCTGAGCCGGGAACCTCAGTTCTCAAAGGGCAGTTTTGCCATTGCGAGAATAGGCCATTTGAGCAATTGCGGTAATAGGCCGTTTCGGCCAAATTTCTTCTTGGTGTCACTCTTCAGGAAAAGAGAG 而言,问题表中有多个具有相同displayOrder的记录,这些插入会导致插入失败。仅其中一个(任何人,但最好是TOP 1)需要进入清单表。 查询有什么方法可以跳过约束并插入其余记录。还是我可以在insert中修改我的select子句?我也尝试过但没有成功。 SELECT可能会为Questions表中的相同displayOrder提取一条以上的记录,并尝试一次将它们插入。

2 个答案:

答案 0 :(得分:1)

插入之前,您应该过滤错误的数据

INSERT INTO Checklist (AuditID, QType, Question, QNmbr, QID, ANmbr)  
  SELECT @AuditID, @QType, Question, displayorder AS QNmbr, id AS QID, 0 AS ANmbr 
  FROM Questions Q 
  left join Checklist C on C.AuditID = @AuditID and c.QType = @QType and C.QNmbr = Q.displayorder and ANmbr = 0
  WHERE Q_type = @QType and c.AuditID is null

我建议您重新考虑您的PK,也许只使用一个增量列即可。

答案 1 :(得分:0)

主键可确保您的数据整洁并防止重复,因此最好不要绕过它。看着您的选择,您几乎已经到了,只是做了一些调整:

INSERT INTO Checklist (AuditID, QType, Question, QNmbr, QID, ANmbr)  
  SELECT DISTINCT @AuditID, @QType, Question, displayorder AS QNmbr, id AS QID, 0 AS ANmbr
  FROM Questions Q
  WHERE Q_type = @QType
  AND NOT EXISTS
  (
    SELECT TOP 1 1
    FROM Checklist CL
    WHERE CL.AuditID = @AuditID 
    and CL.QType = @QType 
    AND CL.QNmbr = Q.displayorder
    AND CL.ANmbr = 0
  )