对于每个行,如果存在则更新另一个表行,否则插入新记录

时间:2018-07-10 06:35:40

标签: sql sql-server tsql while-loop

我有一个查询,该查询返回许多行。

在下面的代码中,一个EnrollmentId可以有多个StudentId

SELECT 
    [StudentId]
    , [ennrollmentId]
    , [Name]
    , [StartDate]
    , [Enddate]
FROM 
    [Enrollements]
WHERE 
    [ennrollmentId] = @ennrollmentId;

现在,如果StudentIdEnrollemntId都没有行,并且我想将StartDateEndDateStudentIdEnrollmentId插入到具有这些规则的新表中, StartDate;如果已经存在这样的行,则更新EndDateINSERT INTO [AnotherTable] SELECT * FROM [Enrollements] WHERE [enrollmentId] = @enrollmentId; -- I have enrollmentId as stored procedure parameter

我写了以下查询:

$(document).ready(function(){
  $(document).on("change",".tot_amount",function(){  
  if (this.checked){  
     var servicetext = $(this).closest("tr").find('td').eq(0).find('span').text();
     var totalamt = $('#tot_amount').val();
     if(totalamt != ''){
     $('#tot_amount').val(totalamt + ", " + servicetext); 
     }
     else{
     $('#tot_amount').val(servicetext);
     }  
     
      var $tr = $(this).closest("tr");
      $("#table2 tbody").append("<tr class='servicetr'>" + $tr.html() + "</tr>");
  }  
  else{
   var $tr = $(this).closest("tr");  
   $('#table2').find(".servicetr").each(function(){    
     if($tr.html() == $(this).html())
     $(this).remove();  
   });
  
  }
  });
});

但这总是插入一条新记录,不会更新。

2 个答案:

答案 0 :(得分:3)

这是非合并解决方案

-- Do the update FIRST, because if you INSERT first, then afterwards ALL records will match

UPDATE e1 set [StartDate]=e2.[StartDate],[Enddate]=e2.[Enddate]
    FROM [Enrollements] e1
    INNER JOIN [Enrollements] e2 on e2.[ennrollmentId]=e1.[ennrollmentId] and e2.[StudentId]=e1.[StudentId]

INSERT INTO [AnotherTable]
    SELECT 
        *
    FROM [Enrollements] e1
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM [Enrollements] e2
        WHERE e2.[ennrollmentId]=e1.[ennrollmentId] and e2.[StudentId]=e1.[StudentId]
    )

答案 1 :(得分:0)

-更新该行(如果存在)。

UPDATE at
SET at.StartDate= en.StartDate
, at.EndDate = en.EndDate -- Edited: "," in SQL Server in place of "AND"
FROM [AnotherTable] at
join [Enrollements] en 
ON (en.[ennrollmentId] = at.[ennrollmentId] AND en.[ennrollmentId] = @ennrollmentId)

-如果UPDATE语句失败,则插入行。

IF (@@ROWCOUNT = 0 )  
BEGIN  
    INSERT INTO [AnotherTable]
    SELECT *
    FROM [Enrollements]
    WHERE [enrollmentId] = @enrollmentId; -- EDITED: updated the table,column name
END