我如何返回一个表的列名使用SQL Server 2008?即一个表包含这些列- id,名称,地址,国家,我想返回这些数据。


当前回答

虽然@Gulzar Nazim的回答很好,但在查询中包含数据库名称可能更容易,这可以通过下面的SQL实现。

SELECT COLUMN_NAME, *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'you-table-name' AND TABLE_CATALOG='your-database-name'

其他回答

一种方法是查询syscolumns:

select
   syscolumns.name as [Column],
   syscolumns.xusertype as [Type],
   sysobjects.xtype as [Objtype]
from 
   sysobjects 
inner join 
   syscolumns on sysobjects.id = syscolumns.id
where sysobjects.xtype = 'u'
and   sysobjects.name = 'MyTableName'
order by syscolumns.name
USE [Database]

SELECT TABLE_NAME,
       TABLE_SCHEMA,
       [Column_Name],
       [Data_type]
FROM   INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_SCHEMA = 'dbo'  
DECLARE @col NVARCHAR(MAX);
SELECT @col= COALESCE(@col, '') + ',' + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS WHERE  Table_name = 'MxLocations';
SELECT @col;

试试这个

select * from <tablename> where 1=2

...............................................

这是最简单的方法

exec sp_columns [tablename]