如果value为null则获取先前值sql server 2008

时间:2013-04-02 01:07:05

标签: sql-server tsql

我的桌子看起来像这样

Id Description
5  Null
4  This is a description
3  This is a description
2  Null
1  Null

我需要创建一个update语句,如果前一个值不为null,将更新null值。

Id Description
5  This is a description
4  This is a description
3  This is a description
2  Null
1  Null

非常感谢任何建议或协助。

2 个答案:

答案 0 :(得分:2)

我认为这就是你要找的东西:

update toupdate
set description = updateto.description 
from yourtable toupdate
  join yourtable updateto on updateto.id = toupdate.id - 1
where updateto.description is not null
  and toupdate.description is null;

SQL Fiddle Demo

这会产生以下结果:

ID  DESCRIPTION
5   This is a description
4   This is a description
3   This is a description
2   (null)
1   (null)

编辑:正如Aaron Bertrand的评论所指出的那样。

如果您的ID不是连续的,您可以使用row_number()功能加入而不是ID:

with cte as (
    select *, row_number() over (order by (select null)) rn
    from yourtable
  )
update toupdate
set description = updateto.description 
from cte toupdate
  join cte updateto on toupdate.rn = updateto.rn - 1
where updateto.description is not null
  and toupdate.description is null;

您可以根据需要按标准更改订单。

Updated SQL Fiddle

答案 1 :(得分:1)

执行此类操作的最常见方式(我知道)是自我加入:

-- WARNING: Untested Code
UPDATE YourTable
SET Origin.Description = Proxy.Description
FROM YourTable Origin
JOIN YourTable Proxy
    ON Origin.Id = Proxy.Id - 1
WHERE Origin.Description IS NULL
AND Proxy.Description IS NOT NULL

这会将YourTable加入到自身,以便一行看起来像这样:

Origin.Id | Origin.Description | Proxy.Id | Proxy.Description
------------------------------------------------------------------
        5 |               NULL |        4 | This is a description

修改
如果不保证总是递增ID,那么您将需要使用ROW_NUMBER

;WITH NumberedRows
AS
    (
    SELECT *
        , ROW_NUMBER() OVER(ORDER BY Id) AS [Row #]
     FROM YourTable
     )
SELECT *
FROM NumberedRows Origin
JOIN NumberedRows Proxy
    ON Origin.Id = Proxy.Id - 1
WHERE Origin.Description IS NULL
AND Proxy.Description IS NOT NULL