Hi
In below Stored Procedure i want if 5 Students have passed as parameter & there r only 3 records in Database then it should show also remaining Students in Column with Status as '-'
ALTER PROC [dbo].[USP_SessionBookPlanningRecommendation] --'0','20,21,22'
(
@BookID VARCHAR(max),
@StudentID VARCHAR(max)
)
AS
BEGIN
declare @cols as nvarchar(max)='';
declare @query as nvarchar(max)='';
select @cols = @cols + QUOTENAME(StudentName) + ',' from (Select distinct StudentName from View_SessionBookPlanningRecommendation where StudentID in (select [value] from string_split(@StudentID,','))) as tmp
select @cols = substring(@cols,0,len(@cols))
set @query = 'select [BookId] [Book ID],BookTitle [Book],[ComboBookName],[AmazonURL],[Core RPL],[Lexile],[Session Plan Status],[Negative List],[ClosingStock], ' + @cols + ' from (select [BookID] ,BookTitle,[ComboBookName],[AmazonURL],[Core RPL],[Lexile],[Session Plan Status],[Negative List],Status,[ClosingStock],StudentName from View_SessionBookPlanningRecommendation where (('''+@BookID+'''=''0'' OR [BookId] IN('+ cast(@BookID as varchar(Max))+')))) x pivot
( Max(Status) for StudentName in (' + @cols + ')) piv order by BookTitle';
print @query
execute (@query)
END
GO
Thanks
Naimish MakwanaPosted Apr 26, 2023, 5:21 AM
Try below:
Note that I have added a new parameter, @NumStudents, which specifies the total number of students to display in the result set, including those who do not have a record in the database. The stored procedure creates a temporary table with the specified number of students and left joins it with the pivoted table to include all students in the result set. The REPLACE function is used to replace any null values with "-" in the final SELECT statement.