Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display the table name in the select statement

Tags:

sql-server

I need to display the table name in the select statement. how?

exact question:

we have common columns in two tables. we are displaying the records by using

select column_name from table_name_1 
union
select column_name from table_name_2

But the requirement is, we need to display the source table_name along with the data. consider a,c are present in table_1 and b,d are present in table_2.

we need the output in the following way

eg:

column_name                     table_name
a                                          table_1
b                                          table_2
c                                          table_1
d                                          table_2
.......................................................
......................................................

Is this possible

like image 538
msbyuva Avatar asked Feb 23 '10 19:02

msbyuva


People also ask

How do I get the table name in SQL SELECT query?

To get table names using SELECT statement, use “information_schema. tables”. Let us see an example, wherein we have a database that contains 3 tables. The syntax to get all table names with the help of SELECT statement.

How show all table names in SQL query?

The easiest way to find all tables in SQL is to query the INFORMATION_SCHEMA views. You do this by specifying the information schema, then the “tables” view. Here's an example. SELECT table_name, table_schema, table_type FROM information_schema.

What is SELECT * from table?

An asterisk (" * ") can be used to specify that the query should return all columns of the queried tables. SELECT is the most complex statement in SQL, with optional keywords and clauses that include: The FROM clause, which indicates the table(s) to retrieve data from.


1 Answers

select 'table1', * from table1 
union
select 'table2',* from table2
like image 166
Hassan Syed Avatar answered Nov 02 '22 23:11

Hassan Syed