Skip to content
Advertisement

How to update row if exist and meet more than one condition and insert it otherwise in SQL Server

I’m trying to perform the below code which I have found it in a thread here

UPDATE MyGuests 
SET lastname = 'Doe' 
WHERE id = 2

IF ROW_COUNT() = 0
   INSERT INTO MyGuests (lastname, id) 
   VALUES ('Doe', 2)

The problem is that I need to do the same thing but with the SQL Server query. My main thought here is that if the new read has the same BoxNo and the same SSCC and the same StyleBarcode, then the value in Qty column will be updated by +1. Otherwise, it’ll make a new insert.

I’m thinking to make something like the following code:

UPDATE MyTable 
SET Qty = Qty + 1 
WHERE BoxNo = 1 
  AND SSCC = 15210049000887900 
  AND StyleBarcode = 5210132138457

IF ROW_COUNT() = 0
   INSERT INTO MyTable (SSCC, StyleBarcode, Qty) 
   VALUES (15210049000887900, 5210132138457, 1)

But I couldn’t make it because I don’t have something like the ROW_COUNT() in SQL Server.

Or I don’t know if you can make have it done in another way?

Thanks in advance.

My table:

MyTestTabel

Advertisement

Answer

SQL Server implements the merge syntax, which seems relevant for your use case.

This statement lets you insert or update from one table into a given table , according to well-defined predicates.

For your question, that would be:

merge mytable as t
using (values (15210049000887900,5210132138457,1)) as s(sscc, styleBarcode, qty)
on (t.sscc = s.sscc and t.styleBarcode = s.styleBarcode)
when matched then 
    update set t.qty = t.qty + 1  -- or t.qty = t.qty + s.qty?
when not matched then 
    insert(sscc,styleBarcode,qty) values(s.sscc, s.styleBarcode, s.qty)
;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement