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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Selecte statement with the parameter as the header

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 customer

i wanted the solution to be as
Title
Samp1
Samp2
Samp3

But when io execute the above statement it displays with
@r1
Samp1
Samp2
Samp3

The 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.
Go to Top of Page

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 customer

i wanted the solution to be as
Title
Samp1
Samp2
Samp3

But when io execute the above statement it displays with
@r1
Samp1
Samp2
Samp3

The 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.html

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

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')

Title
000000
000000
000000
000000
000000
000000
000000

Hope this might be useful.

Go to Top of Page

sindhu sarah
Starting Member

34 Posts

Posted - 2011-11-28 : 07:44:53
Thanks for the solution nigelrivett.Just noticed.
Go to Top of Page
   

- Advertisement -