user1831272
user1831272

Reputation: 713

How to fetch a data from all tables from database

I have 3 columns in different tables in database. Tables names and numbers can be anything so I am not able to write query to fetch data from these three columns.

The query:

SELECT first_name, last_name 
FROM (table names) 
WHERE email="[email protected]"

Please help me with this.

Thanks,

Edward

Upvotes: 1

Views: 467

Answers (2)

NigelK
NigelK

Reputation: 8490

You can build your SQL statement dynamically. Something akin to:

DECLARE @SQL VARCHAR(4000)

SET @SQL = 'SELECT first_name, last_name FROM .... etc'

EXEC (@SQL)

So assuming the table names you want to use are passed in as parameters or otherwise looked up from somewhere, you can include them in the query you build up in the @SQL variable.

Upvotes: 2

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79979

You can do this:

SELECT first_name, last_name, FromWhichTable 
FROM
(
   SELECT first_name, last_name, email, FromWhichTable = 1 FROM table_name1 
   UNION ALL
   SELECT first_name, last_name, email, 2                  FROM table_name2
   UNION ALL
   SELECT first_name, last_name, email, 3                  FROM table_name3 
) t
WHERE email="[email protected]"

Upvotes: 0

Related Questions