Search code examples
sqlt-sql

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


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


Solution

  • 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 ,
           C.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/