将列值设置为先前的记录值

时间:2014-11-05 14:29:57

标签: sql sql-server

我有一个查询,我想选择一个记录,以及基于id的记录。对于FirstName的所有NULL记录,我想将FirstName设置为前一个记录的FirstName。 我有成功获取前后值表的代码,但是如何更新值?我已经尝试了下面的代码,但是我得到了这样的错误

The multi-part indentifier "CTE.FirstName" could not be bound

任何人都知道这是什么问题?请注意,我正在使用SQL Server 2008,因此我无法使用LAG或LEAD

 WITH CTE AS (
    SELECT
    rownum = ROW_NUMBER() OVER (ORDER BY p.BusinessEntityID),
    p.FirstName
    FROM Person.Person p
    )
    SELECT
    prev.FirstName PreviousValue,
    CTE.FirstName,
    nex.FirstName NextValue
    FROM CTE
    LEFT JOIN CTE prev ON prev.rownum = CTE.rownum - 1
    LEFT JOIN CTE nex ON nex.rownum = CTE.rownum + 1
    IF(CTE.FirstName IS NULL)
        BEGIN
            UPDATE Person SET FirstName = prev.FirstName 
        END

2 个答案:

答案 0 :(得分:2)

您可以更新cte,因此应该这样做:

WITH CTE AS (
             SELECT
                   rownum = ROW_NUMBER() OVER (ORDER BY p.BusinessEntityID),
                   p.FirstName
             FROM Person.Person p
             )
UPDATE a
SET a.Firstname = prev.Firstname
FROM CTE a
JOIN CTE prev ON prev.rownum = a.rownum - 1
WHERE a.FirstName IS NULL

答案 1 :(得分:1)

您的更新是select的单独声明。如果您想在更新中执行此操作,请尝试:

WITH CTE AS (
     SELECT rownum = ROW_NUMBER() OVER (ORDER BY p.BusinessEntityID),
            p.FirstName
     FROM Person.Person p
)
UPDATE p
    SET FirstName = prev.FirstName 
    FROM CTE p JOIN
         CTE prev
         ON prev.rownum = CTE.rownum - 1
    WHERE CTE.FirstName IS NULL;

此处left join并不重要,因为您只更改FirstName IS NULL的行。 left join会将NULL值设置为自身。