Click here to Skip to main content
15,886,689 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have a SQL query. I need convert it to a stored procedure.

I have created a query of student result along with ranking. This contains a condition as well. My requirement is to convert this query into a stored procedure. The SQL table name student01 containing Roll, Name, Maths, Science, English, Total, Sum, Average, OrderRank as columns.

Please help me out!

What I have tried:

Query:
create table student01
(
Rollno Int null,
Name Varchar (25),
Maths Int,
English Int,
Science Int,
Total Int null,
Average int,
ORDERRANK int
);

insert into student01
values(1,'api',90,80,90,0,0,0)

update student01
set Total = Maths + English + Science;

update student01
set Average = Total/3;

SELECT
Rollno, Name, Maths, English, Science, Total, Average, ORDERRANK,
CASE
WHEN Maths > 35 AND English > 35 AND Science > 35
THEN RANK() OVER (ORDER BY Average DESC)
ELSE 0
END AS StudentRank
INTO
#TEMP
FROM
student01

UPDATE student01
SET ORDERRANK = (SELECT TOP 1 STUDENTRANK FROM #TEMP
WHERE Rollno = student01.Rollno)

DROP TABLE #TEMP

SELECT *
FROM student01
ORDER BY ORDERRANK ASC
Posted
Updated 22-Aug-21 20:05pm

1 solution

Do not attempt to convert that to a stored procedure: it is designed to be run once and once only as it sets up a new table and populates it with "sample data".
Stored procedures are intended to be run multiple times and that will fail on the second and subsequent runs.

Plus, if you are going to copy'n'paste chunks into your code and call it your own, at least try to make it look slightly consistent in style, or it's a dead giveaway ...
 
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