Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining sys.columns and sys.tables on database name

I'm writing a application using a database backend, but I need to find out all the column names and the table they belong to via SQL. I know you can query sys.columns, sys.tables, and sys.databases, but what I want to do is join them all to get something like the below result (basically displaying all columns and tables from the DB):

    +-----------+------------+
    | Tablename | columnname |
    +-----------+------------+
    | Table1    | Id         |
    | Table1    | Name       |
    | Table1    | Owner      |
    | Table2    | Id         |
    | Table2    | Name       |
    | Table2    | True       |
    +-----------+------------+

I've had a good look in the sys schema, but I can't find any parent reference in sys.columns or sys.tables.

like image 218
TechnicalTophat Avatar asked Jun 17 '16 10:06

TechnicalTophat


People also ask

How do I join two tables with different column names in SQL?

Merging tables by columns. Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other).


2 Answers

Randy Minder's answer is the most correct one. But in case if you want to continue with sys.columns and sys.tables join them on object_id.

select   tab.name, col.name
from    sys.columns col
inner join sys.tables tab
    on col.object_id = tab.object_id

You can use this to get the table names from sys.columns table it self.

select object_name(object_id),name 
from sys.columns
like image 85
Sam Avatar answered Sep 28 '22 16:09

Sam


You generally do not want to query the sys.columns or sys.tables (or any system tables) directly. You should be using the INFORMATION_SCHEMA views. These views are the ANSI standard way of querying system tables that could change from release to release. The INFORMATION_SCHEMA views will not change, at least in a breaking way.

SELECT COLUMN_NAME,* 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = <TableName> AND TABLE_SCHEMA= <SchemaName>

Of course, the WHERE clause is optional here and could be omitted to see all columns in all tables etc.

like image 20
Randy Minder Avatar answered Sep 28 '22 15:09

Randy Minder