Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi expert,

I am grateful for your attention.

My Table
id name department   salary
1   ABC              100000
2   ABD Accounts      76000
3   ADE Testing       59000


if i give the column index of department

then I want to get like
department
----------
Accounts
Testing 

How the problem will be solve.

please help.

Thanks in advance.
Posted
Updated 20-Jul-12 0:39am
v2
Comments
Sandeep Mewara 20-Jul-12 7:26am    
Elaborate what you mean here by an example. Also, do share why are you trying to do such thing.

This will work.

SQL
declare @columnname as varchar(500)
declare @tablename as varchar(500)
declare @Columnindex as int
declare @query as nvarchar(max)

--table name
set @tablename='attendance2'

--column index
set @Columnindex=1
select @columnname= COLUMN_NAME from INFORMATION_SCHEMA.Columns
 where ORDINAL_POSITION=@Columnindex and TABLE_NAME=@tablename

set @query='select ' + @columnname +' From '+@tablename
exec sp_executesql @query
 
Share this answer
 
Comments
Kaushik Saha from Kolkata,India 20-Jul-12 8:03am    
Thank you very much.working smoothly by your code.
Santhosh Kumar Jayaraman 20-Jul-12 8:10am    
Thats my pleasure!!!
Use :
SQL
select distinct [department] from [tablename]
 
Share this answer
 
Comments
Kaushik Saha from Kolkata,India 20-Jul-12 6:50am    
Thanks for your answer.But I have to retrieve using columnIndex not columnname
Hi....


U can use below query.


SQL
select distinct(department) from tblname
 
Share this answer
 
Comments
Kaushik Saha from Kolkata,India 20-Jul-12 7:14am    
Thanks for your answer.But I have to retrieve using columnIndex not columnname.
It is already mentioned in my question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900