How can I get column names from a table in SQL Server?

前端 未结 20 1309
既然无缘
既然无缘 2020-11-22 09:29

I want to query the name of all columns of a table. I found how to do this in:

  • Oracle
  • MySQL
  • PostgreSQL

But I also need to know:

相关标签:
20条回答
  • 2020-11-22 10:22
    --This is another variation used to document a large database for conversion (Edited to --remove static columns)
    
    SELECT o.Name                   as Table_Name
         , c.Name                   as Field_Name
         , t.Name                   as Data_Type
         , t.length                 as Length_Size
         , t.prec                   as Precision_
    FROM syscolumns c 
         INNER JOIN sysobjects o ON o.id = c.id
         LEFT JOIN  systypes t on t.xtype = c.xtype  
    WHERE o.type = 'U' 
    ORDER BY o.Name, c.Name
    
    --In the left join, c.type is replaced by c.xtype to get varchar types
    
    0 讨论(0)
  • 2020-11-22 10:23

    You can use the stored procedure sp_columns which would return information pertaining to all columns for a given table. More info can be found here http://msdn.microsoft.com/en-us/library/ms176077.aspx

    You can also do it by a SQL query. Some thing like this should help:

    SELECT * FROM sys.columns WHERE object_id = OBJECT_ID('dbo.yourTableName') 
    

    Or a variation would be:

    SELECT   o.Name, c.Name
    FROM     sys.columns c 
             JOIN sys.objects o ON o.object_id = c.object_id 
    WHERE    o.type = 'U' 
    ORDER BY o.Name, c.Name
    

    This gets all columns from all tables, ordered by table name and then on column name.

    0 讨论(0)
提交回复
热议问题