Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting list of tables, and fields in each, in a database

Tags:

sql

tsql

I'm looking at creating a basic ORM (purely for fun), and was wondering, is there a way to return the list of tables in a database and also the fields for every table?

Using this, I want to be able to loop through the result set (in C#) and then say for each table in the result set, do this (e.g. use reflection to make a class that will do or contain xyz).

Further to this, what are some good online blogs for SQL Server? I know this question is really about using system SPs and databases in Sql Server, and I am ok with general queries, so I'm interested in some blogs which cover this sort of functionality.

Thanks

like image 971
GurdeepS Avatar asked Jan 07 '09 15:01

GurdeepS


People also ask

How do I get a list of tables in a database?

To get a list of the tables in a MySQL database, use the mysql client tool to connect to the MySQL server and run the SHOW TABLES command. The optional FULL modifier will show the table type as a second output column.

How do I get a list of all columns in a database?

You can use following query to list all columns or search columns across tables in a database. USE AdventureWorks GO SELECT t.name AS table_name, SCHEMA_NAME(schema_id) AS schema_name, c.name AS column_name FROM sys. tables AS t INNER JOIN sys. columns c ON t.


2 Answers

Is this what you are looking for:

Using OBJECT CATALOG VIEWS

 SELECT T.name AS Table_Name ,        C.name AS Column_Name ,        P.name AS Data_Type ,        P.max_length AS Size ,        CAST(P.precision AS VARCHAR) + '/' + CAST(P.scale AS VARCHAR) AS Precision_Scale FROM   sys.objects AS T        JOIN sys.columns AS C ON T.object_id = C.object_id        JOIN sys.types AS P ON C.system_type_id = P.system_type_id WHERE  T.type_desc = 'USER_TABLE'; 

Using INFORMATION SCHEMA VIEWS

  SELECT TABLE_SCHEMA ,        TABLE_NAME ,        COLUMN_NAME ,        ORDINAL_POSITION ,        COLUMN_DEFAULT ,        DATA_TYPE ,        CHARACTER_MAXIMUM_LENGTH ,        NUMERIC_PRECISION ,        NUMERIC_PRECISION_RADIX ,        NUMERIC_SCALE ,        DATETIME_PRECISION FROM   INFORMATION_SCHEMA.COLUMNS; 

Reference : My Blog - http://dbalink.wordpress.com/2008/10/24/querying-the-object-catalog-and-information-schema-views/

like image 92
MarlonRibunal Avatar answered Sep 20 '22 13:09

MarlonRibunal


Tables ::

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' 

columns ::

SELECT * FROM INFORMATION_SCHEMA.COLUMNS  

or

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='your_table_name' 
like image 41
ZombieSheep Avatar answered Sep 20 '22 13:09

ZombieSheep