• jarid.lawson (8/6/2013)


    I have a new position where I finally have the long sought after Sr. prefix included. Only time will tell if I truly deserve the prefix, but I believe that I can do the job. One of the things that is different about this position by comparison to my most recent projects / positions is a more formalized deployment / implementation process (THANK GOD FOR THIS!!! :-D). Part of this process is a code review with several other developers that are at least as good as I am...and in many cases better.

    I had my first code review today, and the only real issue anyone had with it (aside from learning naming conventions) involved a bit of code that I have used for years on end:

    Select VariousFields

    Into dbo.TestTable

    From dbo.SourceTable(s)

    ----------

    Set @RecordCount =

    (Select Count(TestTable_PrimaryKey)

    From dbo.TestTable)

    The code goes on to split the logic path based on @RecordCount = 0 vs. @RecordCount > 0. This is a section of code that I could have said I had down as well as tying my own shoes (there is a Ted Talks reference there, and this entire post lines up with it).

    The conversation went something like this:

    Other developer: Why did you use this code here?

    Me: Because I was needing to split the logic path.

    Other developer: Yes, I see that. What I mean was why didn't you use:

    Select VariousFields

    Into dbo.TestTable

    From dbo.SourceTable(s)

    ----------

    Set @RecordCount = @@RowCount

    Me: Because I had never heard of it, thought of it, or seen it before you just typed it.

    This post is meant to remind not just me but everyone who reads this to look at those parts of our code that seem all but written in stone that we will use the same approach each time. Is there a better way to do what you're doing?

    A small advantage in any area of life can sometimes be the difference between adequate results and all star results.

    There's something else that you need to be aware of... although there are certain things that won't change the rowcount, you should get into the habit of never having any other code between the SELECT/INTO (or any other query) and the SET @Variable = @@ROWCOUNT.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)