2013-06-28 33 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