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

前端 未结 20 1644
既然无缘
既然无缘 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: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]'
    

提交回复
热议问题