Dynamic fields in select command

Posted by Guna27 under Sql Server on 12/20/2012 | Points: 10 | Views : 947 | Status : [Member] | Replies : 7

declare @colum varchar(50)
set @colum='I_TechnicalEnglish'
select @colum 'Subject' from Internal1 where RegisterNo=92107134001


when I execute this command it returns the output as like this,

Subject
I_TechnicalEnglish



It is not return the column value instead it returns column name, How to do this

Guna..............


Responses

Posted by: Pavanandey on: 12/20/2012 [Member] Bronze | Points: 25

Up
0
Down
declare @colum sysname
declare @SQL nvarchar(1024)
set @colum='I_TechnicalEnglish'
set @SQL = 'select ' + @colum + ' from table_1'
exec sp_executeSQL @SQL

Thanks
Pavan Kumar
Mark Answer if this fits the need

Guna27, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Pavanandey on: 12/20/2012 [Member] Bronze | Points: 25

Up
0
Down
Mark answer if this helps you

Thanks
Pavan Kumar
Mark Answer if this fits the need

Guna27, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Funda on: 12/20/2012 [Member] Starter | Points: 25

Up
0
Down
DECLARE @sqlCommand varchar(1000)
DECLARE @colum varchar(50)
SET @sqlCommand = 'SELECT ' + @colum + ' as Subjectfrom Internal1 where RegisterNo=92107134001
EXEC (@sqlCommand)

Guna27, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Guna27 on: 12/20/2012 [Member] Starter | Points: 25

Up
0
Down
Thanks for reply, I need to do this without Dynamic sql query.


declare @colum varchar(50)
declare @mark int
set @colum='I_TechnicalEnglish'
set @mark=( select @colum 'Subject' from Internal1 where RegisterNo=92107134001 )

Because, I need to perform some operation with the value contains in @mark variable.



Guna..............

Guna27, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Pavanandey on: 12/20/2012 [Member] Bronze | Points: 25

Up
0
Down
since you have given @colum 'Subject' .. so 'Subject' gives result like science,maths,social

how can you assign this to an int (@mark)

Thanks
Pavan Kumar
Mark Answer if this fits the need

Guna27, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Guna27 on: 12/20/2012 [Member] Starter | Points: 25

Up
0
Down
Yes, it returns the column name only like "I_TechnicalEnglish"
But i need to get the integer value which contain, So how to solve it

Guna..............

Guna27, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Pavanandey on: 12/21/2012 [Member] Bronze | Points: 25

Up
0
Down
how can you get an integer value from a string like science,maths,social etc

Thanks
Pavan Kumar
Mark Answer if this fits the need

Guna27, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response