Update Table If Record Exists Else Insert ?

  • I have a 'Test1' table (with: 'uid' and 'CatFName' and ''CatLName' and 'CatMName' and 'countID' columns)

    and 'Test2' table (with: 'uid' and 'CatFName' and ''CatLName' and 'CatMName' columns).

    When the inserting the records from Test2 to Test1. if the existing record is present then update the count

    else insert as new record.

  • If you're using SQL 2005 (as per the forum you posted in), then you do a two-state "upsert", which just means you do an update on matched records, and then an insert on unmatched records. It's really no more complex than that.

    If you're actually in 2008 by any chance, you can use Merge to do it all at once.

    - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
    Property of The Thread

    "Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon

  • The two-stage method mentioned by GSquared is outlined here.

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply