My application dynamically adds and drops columns from a table. I want to get the current name of the Nth column, and found the following snippet:
However this doesn't work if columns are dropped. If I drop, say, the 4th column, and try and get the name of the new forth column (was the fifth column), the code returns NULL; @NthCol = 5 returns the name of the old 5th (now 4th) column.
Any suggestions welcome.
Code:
Declare @TableName as nVarchar(100);
Declare @NthCol as Int
Select @TableName =N'MyTableName',
@NthCol=3
Select Col_name(object_id(@TableName),@NthCol) ColumnName
Any suggestions welcome.