If exists, update, if not, insert

Answered If exists, update, if not, insert

  • Friday, April 13, 2012 4:27 PM
     
     

    SQL beginner here...

    I have a single table called Stats that holds attributes for multiple servers in our infrastructure.  I have a powershell script running that dumps these values to this table via an Update statement.  If the powershell script finds a machine that doesn't already exist in the table, it won't update anything for that machine, just will pass over it to the next machine in the script.

    My question is this:  Can I setup something (without changing the powershell script) on my SQL instance that will see the update, know that that value doesn't exist and do an insert instead of an update for that row?

    I've looked at INSTEAD OF Insert stuff, but knowing rings a bell for me.

    thanks!

All Replies

  • Friday, April 13, 2012 6:06 PM
     
     Answered
    MERGE is the statement you are looking for.  There is no way to catch an update of a row that does not exist.

    Chuck

  • Friday, April 13, 2012 6:41 PM
     
     Answered
    You will have to change the script. There is no other way. In SQL 2008 and up MERGE is the best solution for the problem.

    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog