我想查询一个表的所有列的名称。我发现如何做到这一点:

甲骨文 MySQL PostgreSQL

但我也需要知道:如何在Microsoft SQL Server(在我的情况下是2008年)中做到这一点?


当前回答

只需运行这个命令

EXEC sp_columns 'Your Table Name'

其他回答

--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

通过使用这个查询,您可以得到答案:

select Column_name 
from Information_schema.columns 
where Table_name like 'table name'

在SQL Server中,可以从INFORMATION_SCHEMA.COLUMNS中选择COLUMN_NAME。

代码如下:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='YourTableName'

这个SO问题缺少以下方法:

-- List down all columns of table 'Logging'
select * from sys.all_columns where object_id = OBJECT_ID('Logging')
SELECT name
FROM sys.columns
WHERE object_id = OBJECT_ID('TABLE_NAME')

TABLE_NAME是你的表