Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using two sql statement. But, i want to get one single row result when i combine both query.

But, now i am getting two rows. the second row, i want to display within the first row using combine columns.

see my query :
SQL
select  
case 
when  monthid = 4  AND yearid = '2011' and typeid ='A' 
  then '2011'  
when  monthid = 3  AND yearid = '2012' and typeid ='A' 
  then '2012' 
end as FinYear

*  from Employee 
  Where 
( monthid = 4  AND yearid = '2011' and typeid ='A' 
) or
(monthid = 3  AND yearid = '2012' and typeid ='A'  
)


What is the problem over here..?
Posted
Updated 4-May-12 9:42am
v4
Comments
Corporal Agarn 4-May-12 15:44pm    
What two records? Could you please give example input and output?

1 solution

Hi,

With the query above yu get 2 rows like:

2011
2012

You want your result to look like:

2011,2012

To do this you need to use a cursor. the cursor will loop through your results and perform an action on them:

SQL
declare @result varchar(max)
declare @rowdata varchar(4)
declare c1 cursor for select  
case 
when  monthid = 4  AND yearid = '2011' and typeid ='A' 
  then '2011'  
when  monthid = 3  AND yearid = '2012' and typeid ='A' 
  then '2012' 
end as FinYear
 
*  from Employee 
  Where 
( monthid = 4  AND yearid = '2011' and typeid ='A' 
) or
(monthid = 3  AND yearid = '2012' and typeid ='A'  
)

open c1
fetch c1 into @rowdata
while @@fetch_status=0
Begin
if @result is null
Select @Result=@rowdata
else
Select @Result=@Result + ','+@rowdata
fetch c1 into @rowdata
End
Close c1
deallocate c1


This will give you the result 2011,2012
 
Share this answer
 

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