Update or Insert (Upsert) in one query for SQL server

Did you ever wonder if it was possible to do an update or insert in one query? Normally you would write a select query and execute some C# code to see if a certain record already exists and if so do an update and if not do an insert. Besides three SQL query executions this also involves a lot of C# code and doesn't feel like a very efficient approach.

One day I was looking for a better way to solve this very common situation and created this query:

UPDATE Table
SET columnOne = 'valueOne', columnTwo = 'valueTwo',
WHERE Identifier = 123456
	IF @@ROWCOUNT = 0
		INSERT INTO Table
		(columnOne, columnTwo) VALUES ('valueOne', 'valueTwo')

So the query tries to update the record and if the @@ROWCOUNT returns 0, nothing was updated and it will do an insert.

Comments (4) -

  • julia robert

    12/16/2015 1:05:55 PM |

    wow....its really awesome and i fire this command and its really work... two in one query submission is very cool......

  • custom essay writing service

    6/8/2017 5:30:30 AM |

    Good news! really... I wish you a good luck with your site and if you ever wanted to write interesting essays just feel free to ask here.

  • Best essay writing service

    1/3/2018 7:18:24 AM |

    Thanks for putting this together, gave me a great idea on how to expand an already budding idea? One of the best posts I have read. I loved it. Thanks for sharing with us.

  • paperown

    2/22/2018 11:53:40 AM |

    <a href="www.paperown.com/.../"; >assignment editing services </a>
    There is a different technique to write an essay but you should follow the path which will lead you to the place where you can find the right way to write the essay. Here Am going to show you about how to write an essay. There is the link to the description which will guide you through the whole process:

  • Cash Advance San diego

    3/27/2018 5:07:00 PM |

    The greater part of these credits are made for just 2 weeks, at which time you should reimburse them in full. The purpose behind this is a payday advance is just intended to enable you to take care of your expenses, on the off chance that you have a crisis, until your next payday.

  • jeuxdecoration

    3/28/2018 9:00:50 PM |

    Great information and also this info is important and great keep going my friend.

  • cash advance online san diego

    4/5/2018 5:03:12 AM |

    While you may not meet all requirements for a conventional credit from a bank, you will probably have the capacity to effectively get an advance from a payday advance organization.

  • essay writing service

    4/17/2018 5:42:03 AM |

    It doesn’t matter if you are from Adelaide or Sydney, with a nationwide reach in essay writing solutions; expect our essay writing service  to help you with your paper anytime, anywhere.

Loading