你需要MERGE語句
request.query('MERGE [mytable] as target USING (SELECT SalesPersonID, TerritoryID FROM OPENROWSET(' +
'\'Microsoft.ACE.OLEDB.12.0\', \'Excel 12.0;Database=D:\\sample\\test\\data\\1540_OPENROWSET_Examples.xls;HDR=YES\', ' +
'\'SELECT SalesPersonID, TerritoryID FROM [SELECT_Example$]\')' +
') as source' +
' ON target.SalesPersonID = source.SalesPersonID' +
' WHEN MATCHED THEN UPDATE SET TerritoryID = source.TerritoryID' +
' WHEN NOT MATCHED THEN INSERT (SalesPersonID, TerritoryID) VALUES (source.SalesPersonID, source.TerritoryID);'
,function(err,recordset){
if(err) console.log(err)
它將更新TerritoryID
如果已使用相同的SalesPersonID
行和插入行如果沒有匹配的mytable
。
如果你需要加入兩個領域改變這種:
ON target.SalesPersonID = source.SalesPersonID
在此:
ON target.SalesPersonID = source.SalesPersonID AND target.TerritoryID = source.TerritoryID
而在這之後 - 刪除此字符串,因爲它不需要了:
'WHEN MATCHED THEN UPDATE SET TerritoryID = source.TerritoryID' +
嗨,謝謝你回答逐行解釋,我試着運行代碼,它給出了一些語法錯誤: – naik3
'{ [RequestError:關鍵字 '爲' 附近的語法不正確。] 名: 'RequestError', 消息: '附近的關鍵字\語法錯誤' 作爲\, 代碼 '': 'EREQUEST', 號:156, LINENUMBER:1, 類:15, 服務器名稱: '本地主機\\ SQLEXPRESS', PROCNAME: '', precedingErrors: [{[RequestError:附近有語法錯誤('] 名: 'RequestError', message:'Incorrect syntax near \'(\'。', code:'EREQUEST', number:102, lineNumber:1, state:1, class:15, serverName:'localhost \\ SQLEXPRESS', procName:''}]}' – naik3
給我一分鐘,我搞砸了代碼格式! – gofr1