0
日期更新临时表,我有两个表:存储过程基于SQL Server中
Teams [Id],[name],[nomatches],[owngoals],[othergoals],[points]
和
Matches[id],[homeid],[outid],[homegoal],[outgoal],[matchdate]
我有触发对INSERT,UPDATE,DELETE
所以Teams
表当前得分表的触发器始终更新。
实施例:
Select * from teams;
结果:
Name NumberOfMatches OwnGoals OtherGoals Points
-------------------------------------------------------
FC Chelsea 33 61 22 68
FC Barcelona 33 46 34 59
FC Man UD 33 57 50 52
问题:
表Matches
具有柱状matchdate
。我想要重新计算当前比分表(与我的触发器也许)在输入日期之前播放的所有游戏。
我不知道如何创建临时表来存储基于Date
参数的重新计算的数据(nomaches,owngoals,其他目标,每个团队的积分)。
我有什么至今:
CREATE PROCEDURE check_scoretable
(
@pDate DATE = NULL
)
as
DECLARE @Date DATE = COALESCE(@pDate,GETDATE())
declare @homeid char(3);
declare @outid char(3);
declare @id int;
SELECT * INTO #temp_table2 FROM teams;
SET NOCOUNT ON; -- copy of the teams table
declare cur CURSOR LOCAL for
select homeid, outid
from matches where matches.matchdate < @Date
open cur
fetch next from cur into @homeid, @outid
while @@FETCH_STATUS = 0 BEGIN
select @homeid;
select @outid;
--Increment number of matches
update #temp_table2 set #temp_table2.nomatches = #temp_table2.nomatches+1 where #temp_table2.id = @homeid;
update #temp_table2 set #temp_table2.nomatches = #temp_table2.nomatches+1 where #temp_table2.id = @outid;
fetch next from cur into @homeid, @outid
END
close cur
deallocate cur
-- Test the stored procedure
DECLARE @d DATETIME
SELECT @d = GETDATE()
EXEC check_scoretable @date = @d
你必须使用存储过程和游标吗?这是一个简单的查询,没有游标开销。 – Sparky
你能多解释一下吗?我必须使用带有日期参数的存储过程。 – user2988649