2012-05-28 47 views
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/select语句将数据添加到表,你怎么能限制数据以确保它不违反两个密钥?

所以,如果你插入到这个上面的表格:

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,“date”。合理?

干杯, 马特

+2

表*不*有两个主键 - 它有一个*单*,复合主键。您可以*只*在SQL中拥有一个主键(尽管您可以拥有其他键,但必须将其声明为唯一键约束)。 –

回答

3

EXCEPT

返回任何不同的值查询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 
+0

我刚刚在帖子里提到了几乎相同的解决方案。 :)但你击败了我,所以我只给你一个+1 – Johan

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 
        )