Reputation: 3167
Any idea why this code doesn't work in Sql Server please?
CREATE PROCEDURE sum_salaries(OUT sum INTEGER)
LANGUAGE SQL
BEGIN
DECLARE p_sum INTEGER;
DECLARE p_sal INTEGER;
DECLARE c CURSOR FOR SELECT SALARY FROM EMPLOYEE;
DECLARE SQLSTATE CHAR(5) DEFAULT '00000';
SET p_sum = 0;
OPEN c;
FETCH FROM c INTO p_sal;
WHILE(SQLSTATE = '00000') DO
SET p_sum = p_sum + p_sal;
FETCH FROM c INTO p_sal;
END WHILE;
CLOSE c;
SET sum = p_sum;
END%
It gives all sorts of errors:
Msg 102, Level 15, State 1, Procedure sum_salaries, Line 3 Incorrect syntax near 'OUT'. Msg 155, Level 15, State 2, Procedure sum_salaries, Line 6 'INTEGER' is not a recognized CURSOR option. Msg 155, Level 15, State 2, Procedure sum_salaries, Line 7 'INTEGER' is not a recognized CURSOR option. Msg 155, Level 15, State 2, Procedure sum_salaries, Line 9 'CHAR' is not a recognized CURSOR option. Msg 102, Level 15, State 1, Procedure sum_salaries, Line 15 Incorrect syntax near 'p_sal'. Msg 102, Level 15, State 1, Procedure sum_salaries, Line 17 Incorrect syntax near 'DO'. Msg 102, Level 15, State 1, Procedure sum_salaries, Line 19 Incorrect syntax near 'p_sal'. Msg 102, Level 15, State 1, Procedure sum_salaries, Line 24 Incorrect syntax near '='.
Alternatively if you can point me to an ample article/site that teaches the use of cursors, that would be great too. This example was taken from: http://publib.boulder.ibm.com/infocenter/db2luw/v9r5/index.jsp?topic=%2Fcom.ibm.db2.luw.apdv.routines.doc%2Fdoc%2Fc0024361.html&resultof=%22%63%75%72%73%6f%72%22%20
Thank you very much in advance!
Upvotes: 0
Views: 1011
Reputation: 117370
you don't need cursor to do that
create procedure sum_salaries
(
@sum int output
)
as
begin
select @sum = sum(salary) from employee
end
But if you want to use cursor, try that
create procedure sum_salaries
(
@sum int output
)
as
begin
declare @p_sum int, @p_sal int
declare c cursor for
select salary from employee
set @p_sum = 0
open c
fetch from c into @p_sal
while @@fetch_status = 0
begin
set @p_sum = @p_sum + @p_sal
fetch from c into @p_sal
end
close c
deallocate c
set @sum = @p_sum
end
Upvotes: 2