更新多个选定行的值

时间:2017-07-07 08:44:31

标签: sql sql-server

我有2张桌子。两者都有相同的行数。

示例数据:

Table1{
    Id, IdTable2Row
} 

Table2 {
    Id, RedChicken -- LOL
}

Table1的每一行(列IdTable2Row)应该得到表2的1行的id(与哪一行无关)。 Table1.IdTable2Row在操作之前的每一行都为空。

我该怎么办?

UPDATE Table1 SET IdTable2Row = (SELECT Id FROM [Table2])

3 个答案:

答案 0 :(得分:1)

update T1
set idtablerow = t2.id
from Table1 T1
inner join Table2 T2
on T1.something = T2.something

在您的情况下,没有共同的列:

with T1 as
(
select Table1.*, row_number() over (order by anycolumn) rn
from Table1
)
update T1 
set idtablerow = t2.id
from T1
inner join 
(
select x1.*, row_number() over (order by id) rn
from Table2 x1
) T2
on t1.rn = t2.rn

应该工作

答案 1 :(得分:1)

如果我理解正确,你需要匹配第1行到第1行。这是我提出的解决方案:

declare @Table1 table(
    Id INT, 
    IdTable2Row INT NULL
)

declare @Table2 table(
    Id INT, RedChicken varchar(10) -- LOL
)

INSERT INTO @Table1
    VALUES
    (
        1,NULL
    ),(
        2,NULL
    ),(
        3,NULL
    );

INSERT INTO @Table2
    VALUES
    (
        10,'s'
    ),(
        20,'a'
    ),(
        30,'b'
    );


SELECT * 
FROM @Table1 ;
SELECT *
FROM @Table2;


WITH cte1 AS
(
SELECT 
ROW_NUMBER() over(ORDER by Id)  AS rown
,Id
,IdTable2Row
FROM @Table1
),
cte2 AS
(
SELECT ROW_NUMBER() over(ORDER by Id) AS rown
 ,Id
 ,RedChicken
FROM @Table2
)
UPDATE t
SET IdTable2Row = c2.Id
FROM @Table1 t
JOIN cte1 c1 ON c1.Id = t.Id
JOIN cte2 c2 ON c1.rown = c2.rown

SELECT *
FROM @Table1

答案 2 :(得分:-1)

在SQL SERVER中,如果有公共列,则可以加入表并更新

update a set a.IdTable2Row=b.Id from 
Table1 a ,Table2 b
where a.column=b.column