Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
sindhu sarah
Starting Member
34 Posts |
Posted - 2011-11-28 : 05:42:13
|
Hi all,i need a solution for the following query.declare @r1 as varchar (5) set @r1='Title' select name as @r1 from customeri wanted the solution to be as TitleSamp1Samp2Samp3But when io execute the above statement it displays with@r1Samp1Samp2Samp3The above solution needs to be made in an union all query with a diffrent sql statement.Please let me know how to retrieve the header value from variable and display it with the other column.Hope its clear or else please let know.I can explain in more depth.Thanks in advance. |
|
nigelrivett
Master Smack Fu Yak Hacker
3385 Posts |
Posted - 2011-11-28 : 05:48:12
|
declare @sql varchar(8000)select @sql = 'select name as [' + @r1 + '] from customer'exec (@sql)This has security implications though.==========================================Cursors are useful if you don't know sql.SSIS can be used in a similar way.Beer is not cold and it isn't fizzy. |
 |
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2011-11-28 : 07:07:14
|
quote: Originally posted by sindhu sarah Hi all,i need a solution for the following query.declare @r1 as varchar (5) set @r1='Title' select name as @r1 from customeri wanted the solution to be as TitleSamp1Samp2Samp3But when io execute the above statement it displays with@r1Samp1Samp2Samp3The above solution needs to be made in an union all query with a diffrent sql statement.Please let me know how to retrieve the header value from variable and display it with the other column.Hope its clear or else please let know.I can explain in more depth.Thanks in advance.
The above code is not valid statement becuase you cannot use variable as alias name. Noty sure why you did not get any error.Also make sure to read this www.sommarskog.se/dynamic_sql.htmlMadhivananFailing to plan is Planning to fail |
 |
|
sindhu sarah
Starting Member
34 Posts |
Posted - 2011-11-28 : 07:43:05
|
Thanks for your reply madhivanan.i got solution.This can be solved by dynamic query.declare @r1 as varchar (5)set @r1='Title'declare @Query1 nvarchar(4000)exec ('select Dimension6_ as '+ @r1+' from LedgerTrans')Title000000000000000000000000000000000000000000Hope this might be useful. |
 |
|
sindhu sarah
Starting Member
34 Posts |
Posted - 2011-11-28 : 07:44:53
|
Thanks for the solution nigelrivett.Just noticed. |
 |
|
|
|
|