[英]IF NOT EXISTS statement not working correctly after 1st execution
我試圖將數據插入到另一個表feed.tempXML表feed.author。 第一次執行此語句時,它工作得很好,但是當我在feed.tempXML中添加數據並再次運行它時,不會將新作者添加到feed.author表中。 IF語句是否需要更改?
碼:
IF NOT EXISTS(SELECT DISTINCT t.author FROM feed.tempXML t
JOIN feed.author a ON a.author = t.author)
INSERT INTO feed.author(author)
SELECT DISTINCT author
FROM feed.tempXML
WHERE author IS NOT NULL
您的查詢中的問題是,在IF
條件下,您檢查記錄是否存在,但在插入時卻沒有這樣做。
應該這樣做
INSERT INTO feed.author
(author)
SELECT DISTINCT author
FROM feed.tempXML t
WHERE NOT EXISTS (SELECT 1
FROM feed.author a
WHERE a.author = t.author)
AND t.author IS NOT NULL
如果我正確理解您的問題,為什么不使用EXCEPT
?
INSERT INTO feed.author (author)
SELECT author
FROM feed.tempXML
WHERE author IS NOT NULL
EXCEPT
SELECT author
FROM feed.author;
這將從feed.tempXML
中插入feed.tempXML
中尚不存在的feed.author
另外,如果記得'feed.tempXML'表中的'author'可以有空字符串(從理論上講,在您的情況下可能沒有),因此明智的IS NOT NULL
用> ''
替換IS NOT NULL
。 因此查詢變為:
INSERT INTO feed.author (author)
SELECT author
FROM feed.tempXML
WHERE author > ''
EXCEPT
SELECT author
FROM feed.author;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.