Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Select from a table returned by a query as list of table names

If I have these tables below:

PLAYERS

ID    Name
==    ===========
1     Mick
2     Matt

COACHES

ID    Name
==    ===========
1     Bill
2     Don

And I have a script below to find all tables that has a column called "Name":

SELECT t.name AS table_name FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE 'Name'

Which returns the following:

table_name
===========
PLAYERS
COACHES

How can I select all the rows from both tables returned by the query above?

like image 783
Chris Wijaya Avatar asked Jun 18 '13 02:06

Chris Wijaya


People also ask

How do I get a list of table names in SQL query?

In MySQL, there are two ways to find the names of all tables, either by using the "show" keyword or by query INFORMATION_SCHEMA. In the case of SQL Server or MSSQL, You can either use sys. tables or INFORMATION_SCHEMA to get all table names for a database.

Can SELECT statement retrieve data from table?

SELECT statementsAn SQL SELECT statement retrieves records from a database table according to clauses (for example, FROM and WHERE ) that specify criteria. The syntax is: SELECT column1, column2 FROM table1, table2 WHERE column2='value';

What does SELECT * from table return?

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.

How do I list all tables in a selected database?

MySQL SHOW TABLES command example To use the SHOW TABLES command, you need to log on to the MySQL server first. On opening the MySQL Command Line Client, enter your password. Select the specific database. Run the SHOW TABLES command to see all the tables in the database that has been selected.


1 Answers

You will have to use dynamic sql, try something like this:

declare @t table( tablename varchar(50))
declare @sql varchar(max)
set @sql = ''

insert into @t
SELECT t.name AS table_name FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE 'Name'

select @sql = @sql + 'Select * From ' + tablename + ' union ' from @t

--remove the trailing 'union'
Select @sql = substring(@sql, 1, len(@sql) - 6)

exec (@sql)

The above script creates and executes the following sql

select * from coaches
union
select * from players

Since we are using union here, it is important that all your tables that have name as column is of same structure.

See more about dynamic sql from http://msdn.microsoft.com/en-us/library/ms188001.aspx

like image 122
unlimit Avatar answered Nov 14 '22 21:11

unlimit