更新临时表中具有不同值的每一行

时间:2012-10-25 11:53:54

标签: sql sql-server tsql

我有一个列需要使用临时表中的代码进行更新。临时表中有+/- 5个代码。必须使用临时表中的一个值更新表中的每一行。

Example
id  code
1   200
2   400
3   600
4   9000
5   800
6   200
7   400
8   600
9   9000
10  800

3 个答案:

答案 0 :(得分:1)

要获得行集,您需要试试这个

declare @cnt int

select @cnt = count(*) from codes

select M.id, C.Code
from
(
    select
        T.id, (row_number() over (order by id) - 1) % @cnt + 1 as RowNum
    from T as T
) as M
    left outer join
    (select Code, row_number() over (order by Code) as RowNum from codes as T) as C
        on C.RowNum = M.RowNum

http://sqlfiddle.com/#!3/cbd84/1

答案 1 :(得分:0)

SQL Server解决方案

此查询将按顺序获取temp表中的值,并以循环方式更新示例表中的代码,并在需要时重复temp的值。

update e
set code = t.code
from example e
join temp t on t.id = (e.id -1) % (select count(*) from temp) + 1

如果两个表中的ID不是连续的,那么您可以先row_number(),例如

update e
set code = t.code
from (select *,rn=row_number() over (order by id) from example) e
join (select *,rn=row_number() over (order by id) from temp) t
  on t.rn = (e.rn -1) % (select count(*) from temp) + 1

可以在其他RDBMS中使用相同的技术(mod,row-number),但语法会有所不同。

答案 2 :(得分:0)

不同的方法: 假设您要更新的表名为Example。 一个简单的Oracle Merge就是。

Merge INTO Example Using Temp_Table ON Example.Id = Temp_Table.Id
When Matched Then
UPDATE Example
SET Example.code = Temp_Table.code
From Example
Inner Join
Temp_Table
ON
Example.Id = Temp_Table.Id
When Not Matched Then
Insert Into Example 
Select * From Temp_Table
相关问题