Solved

Get the table name in Union Select too?

Posted on 2014-04-28
4
492 Views
Last Modified: 2014-04-28
Hello,

I am trying to query several tables that have the same 3 columns and combine the results like this.

Select col1,col2,col3 from tblA
union
Select col1,col2,col3 from tblB
union
Select col1,col2,col3, from tblC

From
The end result who not only show me the union of three columns form all the tables but also - which is there source table as well like this

Col1 | col2 | col3 | myTableName
Er | ty | rt } tblA
Er | ty | rt } tblB
0
Comment
Question by:Rayne
  • 2
4 Comments
 
LVL 22

Accepted Solution

by:
plusone3055 earned 400 total points
Comment Utility
yes
Select col1,col2,col3, Tbla as tablename  from tblA
union all
Select col1,col2,col3, tblb as tablename from tblB
union all
Select col1,col2,col3, tblc as tablename from tblC
0
 
LVL 69

Assisted Solution

by:ScottPletcher
ScottPletcher earned 100 total points
Comment Utility
Select col1,col2,col3, 'tblA' AS table_name from tblA
union all
Select col1,col2,col3, 'tblB' from tblB
union all
Select col1,col2,col3, 'tblC' from tblC
order by col1, col2, col3
0
 
LVL 22

Expert Comment

by:plusone3055
Comment Utility
hehehe I won by 11 seconds LOL
0
 

Author Closing Comment

by:Rayne
Comment Utility
thank you both :)
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
The viewer will learn how to use the =DISCRINV command to create a discrete random variable, use this command to model a set of probabilities and outcomes in a Monte Carlo simulation, and learn how to find the standard deviation of a set of probabil…
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

772 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

10 Experts available now in Live!

Get 1:1 Help Now