2013-06-28 24 views
0

我想insert from Table1 the rows are not in Table2.SQL:INSERT INTO忽略是否存在

的事情是错误的有节点与parentId = 0在表2。

所以我需要从所有父母的所有儿子都在表2和insert他们,如果他们不是在Table2与父母曾用于表2上的密钥。

我为每个表有两个键,而不只是一个。有我的问题。

如果有人可以给我手,我可以使用cursors

Table1 
IDNode, IDParent 
1  0 
2  1 
3  1 
4  1 
5  0 
6  5 


Table2 
IDNode, IDKey 
1  1 
1  7 
2  6 
4  2 
5  3 





IdNode IDparent IDkey 
2  1   1 
3  1   1 
4  1   1 
2  1   7 
3  1   7 
4  1   7 
remove the IDNode2 with IDKey6 
remove the IDNode4 with IDKey2 
6  5   4 

父亲更重要的是,如果在我的表2我有一个关键的父母,我需要找到形式table1的儿子,与父亲的钥匙插入其中的关键,如果存在与儿子不同的键删除它,毕竟删除表2中的父节点

+0

hi..i觉得对于表2,你是显示这里是confusing..please说清楚的结果.. – user1102001

+0

“插入他们,如果他们不在表2与父母曾用于表2的密钥“ - 不是最清楚的描述 - 但这解释了它。 –

+0

我认为4的样本结果不正确,但 - 不应该是1? –

回答

1

注意:这个答案对你正在使用的SQL的提供者/版本进行了假设。

DECLARE @temp table (idnode, idkey) 

INSERT INTO @temp 
SELECT 
    item.idnode, table2.idkey 
FROM 
    Table1 item 
    inner join Table1 parent on item.idparent = parent.idnode 
    inner join Table2 on table2.idnode = parent.idnode; 


SELECT * from @temp; 

这将返回期望的结果,检查完,这是正确的:

这接下来的部分假定您要删除现有的非匹配项...

DELETE from table2; 

insert into table2 
select * from @temp; 

保留现有的值:

insert into table2 
select t.* from @temp t 
left outer join table2 on table2.idnode = t.idnode 
where table2.idnode is null 
+0

我不知道,但不工作......它没有返回我所有的数据。 – user2528557

+0

对不起,我误读并正在清理现有数据...是第二个选择更好吗? –

+0

我认为最好是从父项中获取所有儿子,然后将它们插入到table2上使用相同的父项,然后使用不同的项删除父项并删除存在于table2上的子项。我怎么能这样做? – user2528557