带有多个语句的SQL过程

时间:2011-09-11 14:16:21

标签: sql

我的SQL经验很少,所以这个问题可能有点明显,但从我读过的内容来看,我似乎正在使用BEGIN / END。我正在使用BEGIN / END以便连续执行多个语句。目标是从表中删除先前的“赢家”,然后使用新的“赢家”计算并填充表格。该表应该只有一个记录;获胜者,冠军。无论语句是如何构造的,我都无法通过第一个有效语句处理任何事情。

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

3 个答案:

答案 0 :(得分:2)

这适用于MsSql服务器

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

答案 1 :(得分:0)

如果您的RDBMS是SQL Server,请使用以下语法:

CREATE PROCEDURE <name>
AS
BEGIN
  <sql_statement>;
  <sql_statement>;
  <sql_statement>;
END

您必须在“BEGIN”之前添加“AS”关键字。

答案 2 :(得分:0)

这应该适用于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 ;

问题是在mySQL中,是分隔符,因此当工作台看到它时,它会尝试结束该过程。通过将分隔符更改为其他内容,您可以创建该过程。之后,您可以恢复原始语句分隔符。