How do I display the table name for each record in the result set ? sql Union

Posted on 2010-01-04
Last Modified: 2012-05-08
Let say i'm doing a union on two or more identical tables...

I want to return all the fields, and also the name of the table the record belongs to.


Select *,{tablename} FROM table1
Select *,{tablename} FROM table2

So that the result would show...
field1data, field2data, table1
field1data, field2data, table2
field1data, field2data. table1

This way I know what table the record came from...

I know there has got to be an easy way to do this... because i've seen it done before...I just don't remember how.
Question by:Ron M
    LVL 75

    Accepted Solution

    Select *, 'table1' as tableName  FROM table1
    Select *, 'table2'   FROM table2
    LVL 25

    Author Comment

    by:Ron M
    I guess that's easy

    I had a DUH moment there.

    I was thinking there was some give the name of the db object...but this works just as well.
    It's just that I have to concatenate a bit more, while building a statement in my .net code.
    LVL 75

    Expert Comment

    by:Aneesh Retnakaran
    > give the name of the db object
    there is one unfortunately you have to pass the object_id
    LVL 25

    Author Comment

    by:Ron M
    Cool... Thanks.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    SQL Command Tool comes with APEX under SQL Workshop. It helps us to make changes on the database directly using a graphical user interface. This helps us writing any SQL/ PLSQL queries and execute it on the database and we can create any database ob…
    Read about achieving the basic levels of HRIS security in the workplace.
    Video by: Steve
    Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
    Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now