Pages

Sunday, May 4, 2014

Get Nth column in a table

--If you want to Fetch the nth column name (only name)
Declare @TableName as nVarchar(100);
Declare @NthCol as Int
Select
          @TableName =N'Sysobjects',
          @NthCol=2
select Col_name(object_id(@TableName),@NthCol) ColumnName


Code Snippet
--If you want to select Record for given Column (with data)
Declare @TableName as nVarchar(100);
Declare @NthCol as Int

Select
          @TableName =N'Sysobjects',
          @NthCol=2
Declare @ColName as varchar(100);
select @ColName = Col_name(object_id(@TableName),@NthCol)

Exec ('Select ' + @ColName + ' From ' + @TableName)

No comments:

Post a Comment