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

I have doubt for writing query in sql for assigning alias of column names using another column values that i mentioned below:
Table1 
Id     FName   Lname
1      peter    pt
2      shiv     sh

Table2
attribute     Displayname
FName         FirstName
Lname         LastName

So the output what i want is like below
Id    FirstName      LastName
1      peter           pt
2      shiv            sh

I tried for using below query but i dint get it:
SQL
select Id,FName as (select Displayname from Table2 where attribute='FName'),
Lname as (select Displayname from Table2 where attribute='Lname')
from Table1


Please help me out
Posted
Updated 15-Sep-12 9:40am
v2

You can not do this in a single t-sql statement. There are other ways, like described here: http://pratchev.blogspot.hu/2008/02/column-alias-based-on-variable.html[^]
But why do you need to do this? Is there no other layer above the database where you can programatically assign field label?
 
Share this answer
 
Comments
Maciej Los 16-Sep-12 15:49pm    
Interesting link. +5
Not directly using a SELECT statement. You can use dynamic SQL like:
SQL
set @sql = N'SELECT Column1 as ' + GetName(@myVariable) + N' FROM Table1'
exec sp_executesql @sql

But this is not suggestible as dynamic SQL has security implications/management issues.
 
Share this answer
 
Comments
Maciej Los 16-Sep-12 15:50pm    
Agree, 5!
Sandeep Mewara 17-Sep-12 1:22am    
Thanks Mac. :)
As Sandeep Mewara wrote, you need to create GetName function:
SQL
--input parameters: @AttribName


--variable to store description
DECLARE @Description VARCHAR(50)

--get description by attribute name
SELECT @Description = Displayname
FROM Table2
WHERE Attribute = @AttribName

RETURN @Description


Please, read more at: http://msdn.microsoft.com/en-us/library/ms186755.aspx[^]
 
Share this answer
 
Comments
Sandeep Mewara 17-Sep-12 1:22am    
Thanks for filling in the gap! 5! :)
Maciej Los 17-Sep-12 12:31pm    
You're welcome ;)

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



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