我有一个存储过程按日期进行分区,然后为每个日期排序一个字段。这已经过测试并正常工作。当前存储过程删除行(如果存在),然后执行INSERT。我想把它变成一个存储过程,如果行存在则更新INSERT一个新的值。我看了很多有关更新的帖子,其他插入,但一直没能得到正确的更新语法。T-SQL更新else使用Rank()分区函数插入存储过程(SQL 2008)
表定义是
(@SeriesID smallint,
@SymbolID smallint,
@Date smalldatetime,
@Val real)
存储过程我想变成UPDATE别的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
任何人都可以提供如何做到这一点的例子吗?
为什么@SeriesID = 12和@OutputID = 35?后来你说SELECT SELECTID = @OutputID ... WHERE SeriesID = @SeriesID。错字,故意混淆,介于两者之间?另外,您可以指定和/或标记您是否正在使用Microsoft SQL Server(tag = sql-server)以及您正在使用的版本(例如sql-server-2005,sql-server-2008)不具有所有版本的功能的优势。 –
使用sql-server-2008(添加标签) –
SeriesID是要排列的系列的标识。它是存储过程的输入之一。 –