Tuesday, October 26, 2010

list column names for a table

To list the column names for a table:

In SQL Server, we can retrieve these details by two methods.

1. This can be taken from the sys.objects and sys.columns table (Used in SQL Server 2000 and higher versions).
2. Another option is to use INFORMATION_SCHEMA.COLUMNS (This is introduced in SQL Server 2005 and higher version)


Below is the query to achieve the same,

drop table venkat_table
go
create table venkat_table (id int,val varchar(100),val1 varchar(100))

First Option:

SELECT *FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='venkat_table'

Second Option:

Joining sys.objects and sys.columns table based on the object Id.

SELECT C.name,O.* FROM sys.objects O INNER JOIN sys.columns CON O.object_id=C.object_id WHERE O.name='venkat_table'

No comments:

Post a Comment