SQL Server在select查询中迭代并根据条件进行更新

时间:2015-08-04 13:50:03

标签: sql sql-server

我从查询

得到以下结果
empId   totalPoints  addPointsDate  incidentDate
-------------------------------------------------
 1           11        2015-06-04    2015-07-11
 2           12        2015-07-04    2015-08-16
 3           10        2015-08-04    2015-06-14
 4           9         2015-06-14    2015-09-11

如果addPointsDate是5周前我必须更新总积分,而且在此期间我没有任何eventsDate。

我可以使用存储过程执行此操作,还是必须使用sql函数

2 个答案:

答案 0 :(得分:1)

我会使用纯SQL(这只是一个简单的UPDATE语句)或过程 - 函数期望您不需要的返回值。

UPDATE
    pointsTable
SET
    totalPoints = totalPoints + 1
WHERE
    -- More than 5 weeks ago
    DATEDIFF(DAY, addPointsDate, GETDATE()) > 35 -- 5 weeks * 7 days
    AND
    -- No incidents, or incident was before the add points date
    (incidentDate IS NULL OR incidentDate < addPointsDate)

答案 1 :(得分:1)

简单的更新就足够了:

update mytable
set totalPoints = totalPoints + 1
    , addPointsDate = getdate()
where
    addPointsDate <= dateadd(week, -5, getdate()) -- add points was before 5 weeks ago
    and incidentDate < addPointsDate -- last incident was before add points