我有以下正常运行的T-SQL代码(在SQL 2000中):
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)
必须有更优雅的方式来做到这一点。我在这里的同一个脚本中以两种不同的方式引用同一个表。
有什么建议吗?
答案 0 :(得分: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
答案 1 :(得分: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)