2009-08-19 396 views
2

我有下面的T-SQL代碼(在SQL 2000),其功能是否正確:T-SQL語句需要改進

INSERT INTO M2MDATA01.dbo.cspopup (fcpopkey, 
            fcpoptext, 
            fcpopval, 
            fnorder, 
            fcpopacces) 
    SELECT CSP69.fcpopkey, 
      CSP69.fcpoptext, 
      CSP69.fcpopval, 
      CSP69.fnorder, 
      CSP69.fcpopacces 
    FROM M2MData69..CSPOPUP CSP69 
    WHERE CSP69.fcpopkey = 'SHIPVIA' 
      AND NOT EXISTS 
       (SELECT CS01.identity_column 
        FROM m2mdata01..cspopup CS01 
        WHERE CS01.identity_column = CSP69.identity_column) 

那裏只是必須做的更優雅的方式。我在這裏使用同一個腳本引用同一個表的兩種不同方式。

有什麼建議嗎?

回答

2

喜歡這個?

INSERT INTO M2MDATA01.dbo.cspopup (fcpopkey, 
            fcpoptext, 
            fcpopval, 
            fnorder, 
            fcpopacces) 
    SELECT CSP69.fcpopkey, 
      CSP69.fcpoptext, 
      CSP69.fcpopval, 
      CSP69.fnorder, 
      CSP69.fcpopacces 
    FROM M2MData69..CSPOPUP CSP69 
    LEFT 
    JOIN m2mdata01..cspopup CS01 
     ON CSP69.identity_column = CS01.identity_column 
    WHERE CSP69.fcpopkey = 'SHIPVIA' 
     AND CS01.indentity_column IS NULL 
2

你可以做它作爲一個左連接在連接結果爲空:

SELECT CSP69.fcpopkey, 
     CSP69.fcpoptext, 
     CSP69.fcpopval, 
     CSP69.fnorder, 
     CSP69.fcpopacces 
FROM M2MData69..CSPOPUP CSP69 
LEFT JOIN m2mdata01..cspopup CS01 on SC01.indentity_column = CSP69.identity_column 
WHERE CSP69.fcpopkey = 'SHIPVIA' 
     AND CS01.identity_column is null 

雖然在我的經驗表現將推動比代碼的正派更多的最終結果。你也可以做一個不:

SELECT CSP69.fcpopkey, 
     CSP69.fcpoptext, 
     CSP69.fcpopval, 
     CSP69.fnorder, 
     CSP69.fcpopacces 
FROM M2MData69..CSPOPUP CSP69 
WHERE CSP69.fcpopkey = 'SHIPVIA' 
     AND CP69.identity_column not in 
(select identity_column from m2mdata01..cspopup)