SQL服务器 - 遍历表并插入(如果不存在),如果存在则更新

时间:2015-08-31 09:27:05

标签: sql-server stored-procedures

我来自Oracle背景,我使用游标进行行更新。

需要编写循环逻辑的最简单方法。这是方案

portApproachViewModel.prototype.openEmailDialog = function(pa) { this.currentDisplayedDialogEmailDtos(pa.emailDtos); return $('#detailcontainer').dialog({ modal: true, resizable: false, width: 400 }); }; table1_intermediateId和其他人eligVal table2_intermediateId以及其他人inEligVal

我有一个主要表table_main,其中包含3列IdeligValinEligVal以及其他

我想将table1_intermediatetable2_intermediate中的记录插入主表。 但是如果Id已经存在(由于从一个表中插入),我想更新来自第二个中间表的相同记录。

任何建议表示赞赏。

1 个答案:

答案 0 :(得分:0)

我更喜欢使用两个存储过程。一个从table1插入值,如?:

 Begin 
 If Not Exists (Select * from table_main where Id=@Id) 
     Begin 
     Insert into table_main(Id,eligVal) values(@Id,@eligVal)
     End
 End

然后在Id为new时插入新行,或者更新相同内容,如:

Begin
If Not Exists (Select * from table_main where Id=@Id)
    Begin
    Insert into table_main(Id,inEligVal) values(@Id,@inEligVal)
    End
Else
    Begin
    Update table_main Set inEligVal=@inEligVal where Id=@Id
    End
End
相关问题