1

I need to update a record in a table but it is possible that the record does not exist, so I would need to insert the record.

Below is a SQL statement that accomplished my goal by trying to update the record first and if it doesn't exist it performs an insert. What I am wondering if it can be executed directly via ADO.NET command object or does it need to go into a stored procedure.

UPDATE MyTable SET ReservationDate = @ReservationDate WHERE CustomerNumber = XXXX;
IF @@ROWCOUNT=0
  INSERT INTO MyTable (CustomerNumber , ReservationDate) 
  VALUES (@CustomerNumber , @ReservationDate)

If I could execute it via the command object without a stored procedure it would mean one less dependency for deployment time (i.e. deploying the stored procedure).

0

1 Answer 1

2

The MERGE command in T-SQL works for just this scenario

string cmdText = @"MERGE MyTable T
                   USING (SELECT @CustomerNumber As CustomerNumber) as S 
                   ON T.CustomerNumber = S.CustomerNumber
                   WHEN MATCHED UPDATE SET ReservationDate = @ReservationDate 
                   WHEN NOT MATCHED INSERT INTO (CustomerNumber , ReservationDate)  
                                    VALUES (@CustomerNumber , @ReservationDate)";

It is just one string of text wrapped for readability in more lines thanks to the verbatim character @

With MERGE you start defining your TARGET table (T), then you build a pseudotable called SOURCE (S) with the parameter that contains the value for the primary key field in TARGET. Now the two tables are JOINED ON the field CustomerNumber. The product of this join could be MATCHED or NOT MATCHED depending of the previous presence of the record in the TARGET table. The remainder of the query is probably self explanatory, just notice that in the two actions (UPDATE and INSERT) there is no need to repeat the MyTable name (it is the TARGET)

By the way, yes you could pass multiple commands to the SqlCommand separated by a semicolon

Sign up to request clarification or add additional context in comments.

3 Comments

Awesome answer and crystal clear example! I had never known of the Merge command. Thank you!
Could this also work if more then field was used in determining which records were updated/inserted? For example ... what if it was not just CustomerNumber but also VehicleNumber that was used when updating/inserting a reservation? Like if a Customer had multiple vehicles.
Why not? Just prepare the appropriate parameters, use them in building your SOURCE table and adjust the JOIN to match/nomatch the primary key of target. UPDATE or INSERT follows

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.