The correct approach to this is to write the value to the output parameter, then print the value of the output parameter in the stored procedure.
For instance:
ALTER PROC ResultsPoll @pollid INT , @message varchar(max) OUTPUT AS SET @message = '' ... IF(@test IS NOT NULL) BEGIN SET @message = 'Number of students who chose ' +@test +' is:'+' '+CAST (@count1 AS VARCHAR(MAX)) END ... PRINT(@message)
Then in your code the value of the output parameter is extracted.
Update
The above suggestion will only work if there is one status or error message that is returned. Upon closer inspection of the stored procedure, I realized that this does not apply to this stored procedure, since print statements are used to return data to the calling application.
Now that I understand this, I suggest that whenever possible the stored procedure be rewritten as follows:
ALTER PROC ResultsPoll @pollid INT AS SELECT result = 'Number of students who chose ' + MAX(Polls.a1) + ' is: ' + CAST(COUNT(1) AS NVARCHAR(MAX)) FROM Students_answer_Polls INNER JOIN Polls ON Polls.poll_id = Students_answer_Polls.poll_id WHERE Students_answer_Polls.poll_id = @pollid AND Students_answer_Polls.answer = Polls.a1 UNION SELECT result = 'Number of students who chose ' + MAX(Polls.a2) + ' is: ' + CAST(COUNT(1) AS NVARCHAR(MAX)) FROM Students_answer_Polls INNER JOIN Polls ON Polls.poll_id = Students_answer_Polls.poll_id WHERE Students_answer_Polls.poll_id = @pollid AND Students_answer_Polls.answer = Polls.a2 UNION SELECT result = 'Number of students who chose ' + MAX(Polls.a3) + ' is: ' + CAST(COUNT(1) AS NVARCHAR(MAX)) FROM Students_answer_Polls INNER JOIN Polls ON Polls.poll_id = Students_answer_Polls.poll_id WHERE Students_answer_Polls.poll_id = @pollid AND Students_answer_Polls.answer = Polls.a3 UNION SELECT result = 'Number of students who chose ' + MAX(Polls.a4) + ' is: ' + CAST(COUNT(1) AS NVARCHAR(MAX)) FROM Students_answer_Polls INNER JOIN Polls ON Polls.poll_id = Students_answer_Polls.poll_id WHERE Students_answer_Polls.poll_id = @pollid AND Students_answer_Polls.answer = Polls.a4 UNION SELECT result = 'Number of students who chose ' + MAX(Polls.a5) + ' is: ' + CAST(COUNT(1) AS NVARCHAR(MAX)) FROM Students_answer_Polls INNER JOIN Polls ON Polls.poll_id = Students_answer_Polls.poll_id WHERE Students_answer_Polls.poll_id = @pollid AND Students_answer_Polls.answer = Polls.a5
With this, you can simply handle the returned rows, which will have one column named result.
source share