I have little SQL experience, so this question may be a bit obvious, but from what I've read, it seems I am using BEGIN/END correctly. I'm using BEGIN/END in order to have multiple statements execute consecutively. The goal is to delete the previous 'winner' from the table, then calculate and populate the table with a new 'winner'. The table should only ever have one record; the winner. no matter how the statements are structured, I can't get it to process anything past the first valid statement.
create procedure contest.getWinner()
begin
begin
delete from contest.winner
where stars > 0;
end
begin
insert into contest.winner(img, stars, cur_DT)
(SELECT A.img, A.stars, now()
FROM
(
SELECT
I.img,
SUM(I.stars) as stars,
MIN(I.cur_DT) as TieBreaker
FROM
contest.votes as I
GROUP BY I.img
)as A
ORDER BY
A.stars DESC,
A.TieBreaker
limit 1
);
end
end
this should work for MsSql server
create procedure getWinner
as
begin
delete from contest.winner
where stars > 0;
end
begin
insert into contest.winner(img, stars, cur_DT)
(SELECT A.img, A.stars, GETDATE()
FROM
(
SELECT
I.img,
SUM(I.stars) as stars,
MIN(I.cur_DT) as TieBreaker
FROM
contest.votes as I
GROUP BY I.img
)as A
ORDER BY
A.stars DESC,
A.TieBreaker
limit 1
);
End
If your RDBMS is SQL Server, use this syntax:
CREATE PROCEDURE <name>
AS
BEGIN
<sql_statement>;
<sql_statement>;
<sql_statement>;
END
You must add the "AS" keyword before "BEGIN".
This should work in mySQL
delimiter //
create procedure contest.getWinner()
begin
delete from contest.winner
where stars > 0;
insert into contest.winner(img, stars, cur_DT)
(SELECT A.img, A.stars, now()
FROM
(
SELECT
I.img,
SUM(I.stars) as stars,
MIN(I.cur_DT) as TieBreaker
FROM
contest.votes as I
GROUP BY I.img
)as A
ORDER BY
A.stars DESC,
A.TieBreaker
limit 1
);
end; //
delimiter ;
The problem is that in mySQL, the ; is the delimiter character, so when the workbench sees it, it try to end the procedure. By changing the delimiter to something else, you can then create the procedure. Afterwards, you can restore the original statement delimiter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.