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?
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.
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';
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With