274

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.

nazia
  • 75
  • 2
  • 9
Belliez
  • 5,356
  • 12
  • 54
  • 62

20 Answers20

446

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'
Nithin Mohan
  • 750
  • 16
  • 34
Gulzar Nazim
  • 51,744
  • 26
  • 128
  • 170
  • 8
    What is the 'YourSchemaName'? – Drewdin Jul 16 '13 at 01:55
  • 13
    'YourSchemaName' is the schema for the table you're querying against. Example: dbo.myTable, 'dbo' is the schema that 'myTable' belongs to. Schemas make it easier to assign permissions to a grouping instead of each table individually. See this question too: http://stackoverflow.com/questions/1062075/why-do-table-names-in-sql-server-start-with-dbo – jmosesman Nov 26 '13 at 23:01
  • 3
    Dont forget on USE DatabaseName command otherwise you can search in master or different database than you want to – Muflix Feb 24 '15 at 14:53
  • 1
    SELECT COLUMN_NAME,* FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTableName' AND TABLE_SCHEMA='dbo' – Usman Younas Jun 10 '15 at 13:24
128

This is the easiest way

exec sp_columns [tablename]
Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
DiggDev
  • 1,423
  • 1
  • 9
  • 8
  • 3
    If your schema is not dbo, you must pass it as an additional parameter. exec sp_columns [TableName], @table_owner = [schema] – Pradeep Feb 06 '19 at 18:31
35

Something like this?

sp_columns @table_name=your table name
Paul Lefebvre
  • 6,253
  • 3
  • 28
  • 36
17

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
splattne
  • 102,760
  • 52
  • 202
  • 249
  • 1
    Wouldn't it be better to fully write out the join (sysobjects so inner join syscolumns sc on so.id = sc.id)? This seems like a lazy answer at the expense of performance. I could be wrong... – Losbear Oct 05 '17 at 13:58
  • 1
    @Losbear changed it PS: Not lazy, it's just code from 8 years ago. :) In old times (I used SQL Server starting at version 4.2), I used to write SQL queries this way. no performance issues. – splattne Oct 06 '17 at 06:26
13

try this

select * from <tablename> where 1=2

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

  • 1
    Interesting ,but what is the logic behind it? – nilakantha singh deo Apr 03 '18 at 03:16
  • 2
    @nilakanthasinghdeo, the logic is that it will always return zero rows with `WHERE 1=2` and it will still return the column meta-data. If using a programmatic interface such as ODBC, then this column info is accessible as a list/array from the cursor object within the program, which is what I was looking for. It might not make sense in a pure SQL context, but is a succinct approach when connecting to a database via Python/Java/C/etc. – Arthur Hebert-Ryan Mar 29 '19 at 17:53
10

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
HogHunter
  • 111
  • 1
  • 4
7

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%'
Scott K.
  • 189
  • 1
  • 6
7

The following seems to be like the first suggested query above but sometime you have to specify the database to get it to work. Note that the query should also work without specifying the TABLE_SCHEMA:

SELECT COLUMN_NAME
FROM   YOUR_DB_NAME.INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_NAME = 'YOUR_TABLE_NAME' AND TABLE_SCHEMA = 'YOUR_DB_NAME'
Edi Mohseni
  • 71
  • 1
  • 2
3

Why not just try this:

right click on the table -> Script Table As -> Create To -> New Query Editor Window?

The entire list of columns are given in the script. Copy it and use the fields as necessary.

Ajay2707
  • 5,690
  • 6
  • 40
  • 58
angieb1008
  • 47
  • 1
  • 3
    The author likely wanted to know how to get the column names from the table programmatically for use in a stored procedure or other script. – KLee1 Oct 22 '12 at 17:54
  • 1
    The answer states `"I want to return these as data"`, while your answer will get the values, it's likely the OP wants the data at runtime. – StuperUser Oct 22 '12 at 17:54
3
USE [Database]

SELECT TABLE_NAME,
       TABLE_SCHEMA,
       [Column_Name],
       [Data_type]
FROM   INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_SCHEMA = 'dbo'  
RF1991
  • 2,037
  • 4
  • 8
  • 17
1

While @Gulzar Nazim's answer is great, it is probably easier to include the database name in the query, which could be achieved by the following SQL.

SELECT COLUMN_NAME, *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'you-table-name' AND TABLE_CATALOG='your-database-name'
user1036719
  • 1,036
  • 3
  • 15
  • 32
1

You can use the below code to print all column names; You can also modify the code to print other details in whichever format u like

    declare @Result varchar(max)='
            '
            select @Result=@Result+''+ColumnName+'
            '
            from
            (
                select
                    replace(col.name, ' ', '_') ColumnName,
                    column_id ColumnId
                from sys.columns col
                    join sys.types typ on
                        col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
                where object_id = object_id('tblPracticeTestSections')
            ) t
            order by ColumnId
            print @Result

Output

column1
column2
column3
column4

To use the same code to print the table and its column name as C# class use the below code:

    declare @TableName sysname = '<EnterTableName>'
    declare @Result varchar(max) = 'public class ' + @TableName + '
    {'

    select @Result = @Result + '
        public static string ' + ColumnName + ' { get { return "'+ColumnName+'"; } }
    '
    from
    (
        select
            replace(col.name, ' ', '_') ColumnName,
            column_id ColumnId
        from sys.columns col
            join sys.types typ on
                col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
        where object_id = object_id(@TableName)
    ) t
    order by ColumnId

    set @Result = @Result  + '
    }'

    print @Result

Output:

 public class tblPracticeTestSections
 {
   public static string column1 { get { return "column1"; } }

   public static string column2{ get { return "column2"; } }

   public static string column3{ get { return "column3"; } }

   public static string column4{ get { return "column4"; } }

 } 
Kalpesh Dusane
  • 1,477
  • 3
  • 20
  • 27
Atal Kishore
  • 4,480
  • 3
  • 18
  • 27
1
DECLARE @col NVARCHAR(MAX);
SELECT @col= COALESCE(@col, '') + ',' + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS WHERE  Table_name = 'MxLocations';
SELECT @col;
1

I'm not sure if the syscolumns.colid value is the same as the 'ORDINAL_POSITION' value returned as part of sp_columns, but in what follows I am using it that way - hope I'm not misinforming...

Here's a slight variation on some of the other answers I've found - I use this because the 'position' or order of the column in the table is important in my application - I basically need to know 'What is column (n) called?'

sp_columns returns a whole bunch of extraneous stuff, and I'm handier with a select than T-SQL functions, so I went this route:

select    
  syscolumns.name, 
  syscolumns.colid    
from     
  sysobjects, syscolumns  
where 
  sysobjects.id = syscolumns.id and   
  sysobjects.xtype = 'u' and   
  sysobjects.name = '<YOUR_TABLE>' 
order by syscolumns.colid 
Wh1T3h4Ck5
  • 8,399
  • 9
  • 59
  • 79
Jake
  • 11
  • 2
  • I used this method for a long time, but was advised against it. In fact I hit the exact problem I was told I might...it's more likely that new versions of MSSQL will change the syntax. For example it used to be sys.object and sys.columns in the versions I first used this technique on. Supposedly the schema and stored procedure methods are more proof against this... not sure, but so far so good. – RosieC Jul 11 '16 at 13:06
1

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’;
abhinav kumar
  • 1,487
  • 1
  • 12
  • 20
1
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
EdChum
  • 376,765
  • 198
  • 813
  • 562
Rishikesh
  • 11
  • 1
  • 2
    Welcome to SO! But it looks like this question already got a satisfactory answer about three years ago... Also, when posting code, use the {} to highlight it. Have a look at the FAQ, it has some good info on getting started here: http://stackoverflow.com/faq – Valentino Vranken Mar 22 '12 at 12:54
0

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

SELECT COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName'
Marcel Grolms
  • 418
  • 4
  • 6
0
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'TableName'
Vishal Kiri
  • 1,248
  • 1
  • 12
  • 24
0

Since SysColumns is deprecated, use Sys.All_Columns:

Select  
 ObjectName       = Object_Name(Object_ID)  
,T.Name  
,C.*  
,T.*  
From   
           Sys.All_Columns C  
Inner Join Sys.Types       T  On T.User_Type_Id = C.User_Type_Id  
Where [Object_ID] = Object_ID('Sys.Server_Permissions')  
--Order By Name Asc  

Select * From Sys.Types will yield user_type_id = ID of the type. This is unique within the database. For system data types: user_type_id = system_type_id.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
-3
set fmtonly on
select * from yourTable
Jimbo
  • 2,529
  • 19
  • 22