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

前端 未结 20 1347
既然无缘
既然无缘 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 09:57
    SELECT c.Name 
    FROM sys.columns c
    JOIN sys.objects o ON o.object_id = c.object_id
    WHERE o.object_id = OBJECT_ID('TABLE_NAME')
    ORDER BY c.Name
    
    0 讨论(0)
  • 2020-11-22 09:59
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_NAME = 'name_of_your_table'
    
    0 讨论(0)
  • 2020-11-22 10:01
    SELECT name
    FROM sys.columns
    WHERE object_id = OBJECT_ID('TABLE_NAME')
    

    TABLE_NAME is your table

    0 讨论(0)
  • 2020-11-22 10:02

    By using this query you get the answer:

    select Column_name 
    from Information_schema.columns 
    where Table_name like 'table name'
    
    0 讨论(0)
  • 2020-11-22 10:04

    Summarizing the Answers

    I can see many different answers and ways to do this but there is the rub in this and that is the objective.

    Yes, the objective. If you want to only know the column names you can use

    SELECT * FROM my_table WHERE 1=0
    or
    SELECT TOP 0 * FROM my_table
    

    But if you want to use those columns somewhere or simply say manipulate them then the quick queries above are not going to be of any use. You need to use

    SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'Customers'
    

    one more way to know some specific columns where we are in need of some similar columns

    SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE COLUMN_NAME like N'%[ColumnName]%' and TABLE_NAME = N'[TableName]'
    
    0 讨论(0)
  • 2020-11-22 10:05
    select *
    from INFORMATION_SCHEMA.COLUMNS
    where TABLE_NAME='tableName'
    

    This is better than getting from sys.columns because it shows DATA_TYPE directly.

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