Stored Proc help - check for existing record and update if exists else insert new

  • Looking for opinions on a stored proc that checks to see if an existing records exists and updates if it does else inserts a new record.

    Example:

    Create PROCEDURE updateinfo

     @userid int,

     @name varchar(50)

    AS

    if userid exists (select userid from main where userid=@userid) begin

     update statement goes here

    end

    else begin

     insert statement goes here

    end

  • I think you want

    if EXISTS (select userid from main where userid=@userid) begin -- remove 'userid'

     update statement goes here

    end

    else begin

     insert statement goes here

    end

     

  • Alternatively:

    update statement goes here

    if @@ROWCOUNT = 0  -- i.e if no rows were updated

       insert statement goes here

  • Yup, Jesper's way is the most efficient if the update has a higher probability of occurring than the insert. Alternately, if you try the insert and use any dupe-key error to invoke an update, the error mechanics takes more processing (assumption) than the first update/insert flow. We use the Jesper logic in many places.

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

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