Check for Record SP

  • Just a quick easy question for you guys:

    In an SP, the author has the following syntax:

    IF EXISTS (SELECT statement)

    RETURN

    INSERT ....

    This code will check if a record exists, if it does, it leaves the SP. If no record exists it proceeds to the INSERT statement. Is this preferred to giving a SELECT statement and doing one thing if @@RowCount = 0 and another thing if @@RowCount <>0?

    Thanks!!

    Sam

  • Select will be slower than exists.

    Exists returns true or false. A select will return a recordset, which is longer to create (especially if there are many rows in the select).

    And I think it's better to check for existence than to wait for an error and then rollback if the insert should not be made.

  • Thanks! That makes sense.

    Sam

  • One more thing to add.. Exists stops executing its select as soon as a match is found, which is obviously not the case with a select: making it even faster because that can make less rows to retrieve and that not data is read from the data pages (unless a table scan is required).

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

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