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:
Please can any one help in writing stored procedure using pivot for making data from a table as columns
Posted
Comments
Sandeep Mewara 4-Feb-11 6:43am    
What kind of help you are expecting? Did you try yourself? Googled? Read/learnt anything?
Corporal Agarn 4-Feb-11 13:15pm    
I suggest Google rows to columns

1 solution

This stored procedure I written to convert Semester as column
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[StudentSemesterMarks]
@Section_Id int,
@sessionid int

--Surabhi
AS
Declare @dta Varchar(500)
Declare @drt Varchar(1000)
Declare @rt varchar(10)
Declare @cnt int
Declare @daver Varchar(500)
BEGIN
DECLARE @test1 CURSOR
SET @test1 = CURSOR FOR SELECT DISTINCT Semester_Id
FROM L_Student_Semester_Marks_Detail



Select @cnt= Count(distinct Semester_Id) FROM L_Student_Semester_Marks_Detail
Set @dta = ''
Set @drt = ''




OPEN @test1
FETCH NEXT FROM @test1
INTO @rt
print @rt
WHILE @@FETCH_STATUS = 0
BEGIN
Set @dta = @dta + '['+ rtrim(@rt) +'],'
Set @drt = @drt + '+ CASE WHEN ['+ rtrim(@rt) +'] IS NULL THEN 0 ELSE ['+ rtrim(@rt) +'] END '
FETCH NEXT FROM @test1
INTO @rt
END
CLOSE @test1
DEALLOCATE @test1
--Set @dta = '[EAS-101],[EAS-102],[EAS-103],[EEC-101],[EEE-101],[EME-101] '
SET @dta= Substring(@dta,0,Len(@dta))
SET @drt= Substring(lTrim(rTrim(@drt)),2,Len(lTrim(rTrim(@drt))))
print @dta
print @drt

exec ( 'select Student_ID, University_RollNo,Student_Name,Father_Name,Date_of_Birth,Phone,LOCAL_ADDRESS,HPercent,iPercent,BPercent,' + @dta + ',' + @drt + ' as Average
from
(
SELECT * FROM L_Student_Semester_Marks_Detail INNER JOIN
V_2010_Section_StudentO ON L_Student_Semester_Marks_Detail.Student_Id = V_2010_Section_StudentO.Student_Id
WHERE Section_Id = ' + @Section_id + ' AND SESSION_ID= ' + @sessionid + '
) ps
pivot
(
Sum(Marks) for Semester_id in (' + @dta + ')
) as pvt'
)
END
 
Share this answer
 
v4
Comments
m@dhu 5-Feb-11 1:34am    
Wrap the code in pre blocks for readabilty.

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