2012-07-10 62 views
1

可能重複:
Insert statement that checks for duplicate before insert如何檢查是否在另一個表中存在記錄,如果沒有則添加

我想檢查是否在問題日誌存在一個建築ID表使用外鍵b_id。如果它不存在,那麼我想將它添加到問題日誌表中。 我有下面的代碼,但這隻能檢查哪些建築物不在問題日誌表中......我該怎麼做插入?非常感謝。我使用的是SQL Server 2008的

select b.b_id from building 
where not exists(select b.b_id from issue_log as l where b._id = l.b_id) 

回答

5

事情是這樣的:一旦你的語法下來

MSDN這是相當有用嗎?

INSERT INTO issue_log(b_id) 
SELECT b.b_id FROM building b 
WHERE NOT EXISTS(SELECT l.b_id FROM issue_log AS l WHERE b.b_id = l.b_id) 
相關問題