我有一個包含一個表下列:更新(如果存在),否則插入
- PK
- EMPID
- peer_empID
的數據是這樣的:
pk empID peer_empID
1 5 27
2 5 94
3 5 67
數據以這種方式顯示給用戶:
用戶可以添加同行,修改選定的對等,並刪除它們。最後點擊保存:
- 刪除同行將被刪除
- 更改同行將被更新
- 新增同行會增加
,它會被存儲在數據庫中。
我必須編寫一個查詢來更新,如果更改,插入如果不存在,並刪除,如果從前端刪除。
我嘗試這樣:
IF not exists (select empID, peer_empID from assignPeers where empID = @empID and peer_empID = @peer_empID)
BEGIN
insert into assignPeers (empID, peer_empID) values (@empID, @peer_empID)
END
ELSE
BEGIN
update assignPeers set peer_empID = -->here is the problem.. how will I define the condition to update? <--
where empID = @empID and peer_empID = @peer_empID
END
請給我建議在這種情況下怎麼辦?
這是一種非常常見的情況。有關信息的Google'UPSERT'。大多數RDBMS現在都有語法。 – JNK
你看過MERGE聲明嗎? http://msdn.microsoft.com/en-us/library/bb510625.aspx – SchmitzIT
@SchmitzIT我不知道這件事。我檢查出來。 – Shaharyar