How do you return the column names of a table?

2019-01-02 14:50发布

How would I return the column names of a table using SQL Server 2008? i.e. a table contains these columns- id, name, address, country and I want to return these as data.

19条回答
听够珍惜
2楼-- · 2019-01-02 15:13

This is the easiest way

exec sp_columns [tablename]
查看更多
素衣白纱
3楼-- · 2019-01-02 15:13

I use

SELECT st.NAME, sc.NAME, sc.system_type_id
FROM sys.tables st
INNER JOIN sys.columns sc ON st.object_id = sc.object_id
WHERE st.name LIKE '%Tablename%'
查看更多
萌妹纸的霸气范
4楼-- · 2019-01-02 15:13
DECLARE @col NVARCHAR(MAX);
SELECT @col= COALESCE(@col, '') + ',' + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS WHERE  Table_name = 'MxLocations';
SELECT @col;
查看更多
闭嘴吧你
5楼-- · 2019-01-02 15:14

This seems a bit easier then the above suggestions because it uses the OBJECT_ID() function to locate the table's id. Any column with that id is part of the table.

SELECT * 
  FROM syscolumns 
 WHERE id=OBJECT_ID('YOUR_TABLE') 

I commonly use a similar query to see if a column I know is part of a newer version is present. It is the same query with the addition of {AND name='YOUR_COLUMN'} to the where clause.

IF EXISTS (
        SELECT * 
          FROM syscolumns 
         WHERE id=OBJECT_ID('YOUR_TABLE') 
           AND name='YOUR_COLUMN'
        )
BEGIN
    PRINT 'Column found'
END
查看更多
泛滥B
6楼-- · 2019-01-02 15:15

I just use a query like Martin Smith mentioned, just little shorter:

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName'
查看更多
公子世无双
7楼-- · 2019-01-02 15:15
set fmtonly on
select * from yourTable
查看更多
登录 后发表回答