0

如果您有一个包含两个主键的表:

CREATE TABLE [AttributeMap](
[intParentAttributeId] [bigint] NOT NULL,
[intChildAttributeId] [bigint] NOT NULL,
    [datCreatedDate] [datetime] NOT NULL
  CONSTRAINT [PK_AttributeMap] PRIMARY KEY CLUSTERED 
 ( 
   [intParentAttributeId] ASC,
    [intChildAttributeId] ASC
 )

如果要执行插入/选择语句以将数据添加到表中,如何限制数据以确保它不会违反两个键?

因此,如果将其插入上表:

INSERT INTO [AttributeMap] VALUES (1, 1, getdate())
INSERT INTO [AttributeMap] VALUES (1, 2, getdate())
INSERT INTO [AttributeMap] VALUES (1, 3, getdate())
INSERT INTO [AttributeMap] VALUES (2, 1, getdate())

您如何在不违反密钥的情况下运行此查询?

declare table @temp (intParent int, intChild int)
insert into @temp (1, 1)
insert into @temp (1, 2)
insert into @temp (4, 4)
insert into @temp (5, 5)

 insert into AttributeMap (intParentAttributeId, intChildAttributeId, datCreatedDate)
  select intParent, intChild, getDate()
 from @temp

所以 AttributeMap 应该以两个新行结束,值 4, 4, "date" 和 5, 5 "date"。说得通?

干杯,马特

4

2 回答 2

3

EXCEPT

返回操作数左侧查询中的任何不同值,这些值也不是从右侧查询返回的。

尝试这个:

insert into AttributeMap (intParentAttributeId, intChildAttributeId, datCreatedDate)
Select temp.intParent, temp.intChild, getDate()
FROM 
(select intParent, intChild
from @temp 
EXCEPT 
select intParentAttributeId, intChildAttributeId
from AttributeMap) as temp
于 2012-05-28T11:54:37.340 回答
1

您需要手动检查密钥是否已存在并仅在不存在时才插入:

 insert into AttributeMap (intParentAttributeId, intChildAttributeId, datCreatedDate)
 select intParent, intChild, getDate()
   from @temp t
  where not exists (select null
                      from AttributeMap
                     where AttributeMap.intParent = t.intParent
                       and AttributeMap.intChild = t.intChild
                   )
于 2012-05-28T11:48:05.217 回答