How can I get column names from a table in SQL Server?
I would like to query the name of all columns of a table. I found how to do this in:
But I need to know: how can this be done in Microsoft SQL Server (2008 in my case)?
You can obtain this information and much, much more by querying the Information Schema views.
This sample query:
SELECT *
FROM Northwind.INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'Customers'
Can be made over all these DB objects:
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.
select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'
这比从sys.columns
获得更好,因为它直接显示DATA_TYPE
。
上一篇: 在关系数据库中存储分层数据有哪些选项?