How do I include a column with the table name it came from specified in another column

  • I need to be able to insert records into a table from multiple places and be able to specify where each record came from.  In other words:

     

    Insert into EmailList

    Select Name,date,emailaddress,TableName

    from BVC_user

                              The record in the new table would be as follows

                                  John Doe,1/29/2007,JOHN@DOE.com,Bvc_User

     

    I can't figure out how to get the table name.

    any thoughts? I am sure it is probably simple but I haven't been able to figure it out.

  • Just specify it as a string, like this:

    Insert into EmailList

    Select Name,date,emailaddress,'BVC_User' as TableName

    from BVC_user

    UNION ALL

    Select Name,date,emailaddress,'GFD_User' as TableName

    from GFD_user

    UNION ALL

    Select Name,date,emailaddress,'TRE_User' as TableName

    from TRE_user

    Hope this helps...

    Rob Farley
    LobsterPot Solutions & Adelaide SQL Server User Group
    Company: http://www.lobsterpot.com.au
    Blog: http://blogs.lobsterpot.com.au

  • Are you doing this from within a trigger or another function?

  • You can also use the master..sysobjects table. Your table should be there also - as name, id etc. But in fact the way given by Mr.Farley is easier 

    Kindest Regards,

    Damian Widera
    SQL Server MVP,
    MCT, MCSE Data Platform, MCSD.NET

  • I am doing this through a trigger.

     

    Thanks

  • Then you have to use Rob's method... triggers are absolutely oblivious as to what the source of information is so far as table name goes.

    --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)

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

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