使用sql中的选定记录更新现有表

时间:2015-02-11 06:06:41

标签: sql-server-2008 tsql sql-update recordset

我遇到了一个查询,我需要使用动态生成的记录集来更新现有表。我试着寻找答案,但没有得到他们的帮助。

这是我的问题:

with t as
(
    SELECT R.Col1, R.Col2, O.Column2, row_number() 
        OVER (partition by R.Col3, R.Col4 
              ORDER BY
              CASE WHEN @Criteria = 'NA' then R.Col1 END ASC,
              CASE WHEN @Criteria = 'ND' then R.Col1 END DESC,
              CASE WHEN @Criteria = 'CA' then R.Col2 END ASC,
              CASE WHEN @Criteria = 'CD' then R.Col1 END DESC
             ) as NewOrder 
               From RecordsTable R innerjoin OtherTable O on R.Col2 = O.Column1
               where R.Col3 = @Col5Val
)
Update RecordsTable Set RecordsTable.Ordering = t.NewOrder 
       where RecordsTable.Name = t.Col1 
       and RecordsTable.Address = t.Col2

我得到的错误是The multi-part identifier "t.Col1" could not be boundThe multi-part identifier "t.Col2" could not be bound

我不确定查询是否正确,但我想这在某种程度上应该是正确的。

表结构

RecordsTable

Col1   |    Col2    |    Col3    |    Col4   |   Ordering
------------------------------------------------------------
ABC    |   78945    |    8345    |    XYZ    |    1

OtherTable

Column1  | Column2    |    Column3    
-----------------------------------
FOO      |   BAR      |    8345    

注意 需要cases对记录进行排序,因为更新NewOrder需要RecordsTable生成的记录

1 个答案:

答案 0 :(得分:1)

您正在更新CTE中涉及的其中一个表格,但在更新期间您无法将其与CTE相关联。因此,您需要使用更新语句中的内部联接将源表连接回CTE,如下所示:

--CTE here

 Update RecordsTable 
 Set RecordsTable.Ordering = t.NewOrder
 from recordstable r
 inner join t on
 r.Name = t.Col1 and r.Address = t.Col2

或者,您可以在CTE中包含名称,地址和订购列,并直接更新CTE:

    with t as
(
    SELECT R.Col1, R.Col2, O.Column2, R.Name, R.Address, R.Ordering, row_number() 
        OVER (partition by R.Col3, R.Col4 
              ORDER BY
              CASE WHEN @Criteria = 'NA' then R.Col1 END ASC,
              CASE WHEN @Criteria = 'ND' then R.Col1 END DESC,
              CASE WHEN @Criteria = 'CA' then R.Col2 END ASC,
              CASE WHEN @Criteria = 'CD' then R.Col1 END DESC
             ) as NewOrder 
               From RecordsTable R innerjoin OtherTable O on R.Col2 = O.Column1
               where R.Col3 = @Col5Val
)
Update t
Set t.Ordering = t.NewOrder 
where t.Name = t.Col1 
and t.Address = t.Col2

Demo