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.
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.
Not sure if there is an easier way in 2008 version.
USE [Database Name]
SELECT COLUMN_NAME,*
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName' AND TABLE_SCHEMA='YourSchemaName'
One method is to query 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
CREATE PROCEDURE [dbo].[Usp_GetColumnName]
@TableName varchar(50)
AS
BEGIN
BEGIN
SET NOCOUNT ON
IF (@TableName IS NOT NULL)
select ORDINAL_POSITION OrderPosition,COLUMN_NAME ColumnName from information_schema.columns
where table_name =@TableName
order by ORDINAL_POSITION
END
END
IF you are working with postgresql there is a possibility that more than one schema may have table with same name in that case apply the below query
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'your_table_name' AND table_schema = 'your_schema_name’;