Combining data from Column A + Column B into Column C

  • SQL Newbie,

    How do I combine data from Column A + Column B into Column C, the result of Column C

    will be the contents of (Column A + Column B).

    Thanks

    HLopes

  • http://www.windowsitpro.com/SQLServer/Article/ArticleID/22091/22091.html may be what you are looking for.

    olja

  • In a perfect world a database would be used to strictly store data... as we all know we are in a far from perfect world, and databases are becoming more and more application containers within themselves; leaving the web browsers and actual applications to just display data.

    In this case it would be best to have the application owner modify their Select statement to do the calculation at runtime as described in the post above.

    Your other option would be to use a trigger for inserts and updates to the table.  (This will add overhead to your server.)  This is not the best way (or best practice to make a habit of in this type of situation) but we've all been in unique situations so here is a sample trigger to take care of this...

    /*******************************************/

    CREATE TRIGGER  Update_ColC ON myTable

    FOR INSERT, UPDATE

    AS IF (Update(ColA) OR Update(ColB))

    UPDATE myTable

    Set ColC = inserted.ColA + inserted.ColB

    From inserted

    WHERE myTable.KeyCol = inserted.KeyCol

    GO

    /*******************************************/

    Hope this helps.

  • A note on the trigger above:

    It assumes that both ColA and ColB contains a value.  If either ColA or ColB is Null, ColC will also equal Null.

    If these are numeric fields this can be prevented by setting a default value of zero on both ColA and ColB.  This will ensure a value is always in the columns before the calculation is run.

  • Thank you very much for your help, it worked out very well,

    thanks again.

    Best regards, Helder Lopes

     

  • Keep in mind if either ColumnA or ColumnB are NULL, ColumnC will be NULL. 

    (oops, Ghost already said this... sorry - may want to use the ISNULL function...)

    I wasn't born stupid - I had to study.

Viewing 6 posts - 1 through 5 (of 5 total)

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