我有一个包含一个表下列:更新(如果存在),否则插入
- 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