Jes Sie

Jes Sie

  • 704
  • 1.2k
  • 265k

PIVOT with Parameters in Stored Procedure

Mar 16 2018 12:10 AM
Hello DBA's good day. 
 
I tried to create a pivot in stored procedure with parameters. Please code snippet:
 
  1. ALTER PROCEDURE spGet_SummaryOfAttendanceForRegistrar  
  2.     -- Add the parameters for the stored procedure here  
  3.     @SchoolCode nvarchar(50),  
  4.     @SchoolYear nvarchar(50),  
  5.     @TermCode nvarchar(10),  
  6.     @GradeLvlCode nvarchar(10)  
  7. AS  
  8. BEGIN  
  9.     -- SET NOCOUNT ON added to prevent extra result sets from  
  10.     -- interfering with SELECT statements.  
  11.     SET NOCOUNT ON;  
  12.   
  13.     -- Insert statements for procedure here  
  14.     declare @cols varchar(1000)  
  15.     declare @sqls varchar(2000)  
  16.     select @cols = COALESCE(@cols + ', ','') + QUOTENAME(AttendanceDate)  
  17.     from tblStudentAttendance   
  18.     Group by AttendanceDate  
  19.     Set @sqls='select * from (select StudentID, StudentName, AttendanceDate, Attendance from tblStudentAttendance WHERE SchoolCode = ''@SchoolCode'' and SchoolYear = ''@SchoolYear'' and TermCode = ''@TermCode'' and GradeLvlCode = ''@GradeLvlCode'') src   
  20.     PIVOT (Max(Attendance) FOR AttendanceDate   
  21.     IN ('+@cols+')) pvt'    
  22.     EXEC(@sqls)  
  23. END  
  24. GO  
If there are parameters, I can't get any results. But if I will remove the parameters, I get what I want.
 Any help is very much appreciated. Thank you.

Answers (3)