T-SQL存储过程执行两次选择吗?

时间:2019-02-25 17:57:46

标签: sql-server database tsql

DROP PROCEDURE showMatchOnDate
go

CREATE PROCEDURE showMatchOnDate 
     @MatchDate DATE
AS
    DECLARE @tempTeams TABLE
                       (
                           Id CHAR(3) PRIMARY KEY,
                           name VARCHAR(40),
                           nomatches INT,
                           owngoals INT,
                           othergoals INT,
                           points INT
                       )

    INSERT INTO @tempTeams(Id, name, nomatches, owngoals, othergoals, points)
        SELECT * FROM teams

    DECLARE @homeGoals INT
    DECLARE @outGoals INT
    DECLARE @homeID CHAR(3)
    DECLARE @outID CHAR(3)

    DECLARE @count INT
    DECLARE @totalAmount INT

    SET @totalAmount = (SELECT COUNT(*) FROM matches WHERE matchdate <= @MatchDate)
    SET @count = 1

    SELECT @totalAmount

    WHILE (@count <= @totalAmount)
    BEGIN
        SELECT @homeGoals = (SELECT homegoal FROM matches WHERE Id = @count)
        SELECT @outGoals = (SELECT outgoal FROM matches WHERE Id = @count)
        SELECT @homeID = (SELECT homeid FROM matches WHERE Id = @count)
        SELECT @outID = (SELECT outid FROM matches WHERE Id = @count)

        UPDATE @tempTeams
        SET nomatches = nomatches + 1
        WHERE Id = @homeID OR Id = @outID

        UPDATE @tempTeams
        SET owngoals = owngoals + @homeGoals
        WHERE Id = @homeID

        UPDATE @tempTeams
        SET owngoals = owngoals + @outGoals
        WHERE Id = @outID

        UPDATE @tempTeams
        SET othergoals = othergoals + @outGoals
        WHERE Id = @homeID

        UPDATE @tempTeams
        SET othergoals = othergoals + @homeGoals
        WHERE Id = @outID

        UPDATE @tempTeams
        SET points = points + 3
        WHERE Id = @homeID AND @homeGoals > @outGoals

        UPDATE @tempTeams
        SET points = points + 3
        WHERE Id = @outID AND @outGoals > @homeGoals

        IF @outGoals = @homeGoals
            UPDATE @tempTeams
            SET points = points + 1
            WHERE Id = @homeID OR (Id = @outID)

        SET @count = @count + 1
    END

    SELECT * FROM @tempTeams
go

由于某种原因,运行此命令时,我会得到每个项目的副本。我不要显然,我希望正确的值应该是154个不同的项目。但是我得到了308,并且每个项目都是重复的。有人知道为什么吗?

1 个答案:

答案 0 :(得分:0)

首先检查“团队”表,这里可以有其他数据。如果是,请删除重复的数据。

最佳做法还要求编写显式字段,以避免将来出现错误,例如:

insert into @tempTeams(Id,name,nomatches,owngoals,othergoals,points)
   select Id,name,nomatches,owngoals,othergoals,points
   from teams