SELECT table name that is inside UNION

Posted by LexRema on Stack Overflow See other posts from Stack Overflow or by LexRema
Published on 2010-05-14T10:08:13Z Indexed on 2010/05/14 10:14 UTC
Read the original article Hit count: 190

Filed under:

I have two same tables. I need to union them in such way:

SELECT f1,f2, xxx
FROM 
(SELECT     *
FROM         tbl1
UNION ALL
SELECT     *
FROM         tbl2)

where xxx would query for a table name, where f1 and f2 fields are taken from. Example output:

123 345 'tbl1' -- this rows are from the first table
121 345 'tbl1'
121 345 'tbl1'
123 345 'tbl1'
124 345 'tbl1'
125 345 'tbl2' -- this rows are from the second table
127 345 'tbl2'

Thank you in advance.

© Stack Overflow or respective owner

Related posts about t-sql