title: SQL Server foreach loop to read one record at a time from table and then use it to insert or update
body: <p>I have a stored procedure which accepts a table as parameter. The parameter is a table containing details of an order basket (users can save their baskets to do the payment at a later time) I want to loop through each item and update if exists and otherwise insert it. something like:</p>
  
  <pre><code>foreach select @item_id=item_id,@count=item_count from @details
  begin
      if exists(select id from basket_details where item_id=@item_id and basket_id=@id)
           update basket_details set item_id=@item_id,item_count=@count where  item_id=@item_id and basket_id=@id
      else
           insert into basket_details(item_id,item_count) values(@item_id,@count)
  end
  </code></pre>
  
  <p>How can I do this in SQL Server?</p>