我有一个按日期分区然后为每个日期排列一个字段的存储过程。这已经过测试并且可以正常工作。当前存储过程删除行(如果存在),然后执行 INSERT。我想把它变成一个存储过程,如果该行存在则更新,否则插入一个新值。我查看了许多有关Update else Insert的帖子,但未能获得正确的更新语法。
表定义是
(@SeriesID smallint,
@SymbolID smallint,
@Date smalldatetime,
@Val real)
我希望变成 UPDATE else INSERT 的存储过程是:
CREATE PROCEDURE [dbo].[RankPerDate]
@StartDate smallDateTime,
@EndDate smallDateTime,
@SeriesToRankID smallint,
@RankedSerieID smallint
AS
-- remove time series if it exists
BEGIN
DELETE FROM SeriesFloat
WHERE SeriesID = @RankedSerieID AND (Date >= @StartDate) AND (Date <= @EndDate)
END
BEGIN
INSERT INTO SeriesFloat
SELECT SeriesID = @RankedSerieID, SymbolID, Date, RANK() OVER (PARTITION BY Date ORDER BY Val DESC) AS Val
FROM SeriesFloat
WHERE (SeriesID = @SeriesToRankID) AND (Date >= @StartDate) AND (Date <= @EndDate)
END
存储过程示例输入:
-- sample values for testing & parameters for stored procedure
@StartDate = '1999-01-08 00:00:00';
@EndDate = '1999-01-09 00:00:00';
@SeriesToRankID = 12; -- id of the series that is to be ranked
@RankedSerieID = 35; -- id of the series that is to be updated/inserted
查询前的样本表数据:
SeriesID SymbolID Date Val
12 2011 1999-01-08 00:00:00 4215000
12 2012 1999-01-08 00:00:00 3215580
12 2013 1999-01-08 00:00:00 2029895
12 2011 1999-01-09 00:00:00 2029895
12 2012 1999-01-09 00:00:00 3395788
12 2013 1999-01-09 00:00:00 4029895
35 2012 1999-01-09 00:00:00 4 -- this row will be updated
35 2013 1999-01-09 00:00:00 8 -- this row will be updated
排名结果:
SeriesID SymbolID Date Val
35 2011 1999-01-08 00:00:00 1 -- this row is inserted
35 2012 1999-01-08 00:00:00 2 -- this row is inserted
35 2013 1999-01-08 00:00:00 3 -- this row is inserted
35 2011 1999-01-09 00:00:00 3 -- this row is inserted
35 2012 1999-01-09 00:00:00 2 -- this row is updated
35 2013 1999-01-09 00:00:00 1 -- this row is updated
运行存储过程后的示例表数据:
SeriesID SymbolID Date Val
12 2011 1999-01-08 00:00:00 4215000
12 2012 1999-01-08 00:00:00 3215580
12 2013 1999-01-08 00:00:00 2029895
12 2011 1999-01-09 00:00:00 4029895
12 2012 1999-01-09 00:00:00 3395788
12 2013 1999-01-09 00:00:00 2029895
35 2011 1999-01-08 00:00:00 1 -- this row was inserted
35 2012 1999-01-08 00:00:00 2 -- this row was inserted
35 2013 1999-01-08 00:00:00 3 -- this row was inserted
35 2011 1999-01-09 00:00:00 3 -- this row was inserted
35 2012 1999-01-09 00:00:00 2 -- this row was updated
35 2013 1999-01-09 00:00:00 1 -- this row was updated
谁能提供一个如何做到这一点的例子?