当表格没有关联时,如何从另一个表中按顺序更新表格的列

时间:2017-08-01 05:48:21

标签: sql-server tsql

当表格没有通过唯一键相互关联时,我不确定如何从SQL Server中的另一个表更新列的值。

A

+--------+--------+--------+
| Id     | col2_A | col3_A |
+--------+--------+--------+
| 1      |      3 | 5      |
| 2      |      3 | 3      |
| 3      |      3 | 2      |
| 4      |      3 | 1      |
| 5      |      3 | 8      |
+--------+--------+--------+

+--------+--------+
| Id     | Col1_B |
+--------+--------+
|     11 |    6   |
|     12 |    7   |
|     13 |    8   |
|     14 |    9   | 
|     15 |   10   | 
+--------+--------+

必填结果:

+--------+--------+--------+
| Id     | col2_A | col3_A |
+--------+--------+--------+
| 1      |      1 |      6 |
| 2      |      1 |      7 |
| 3      |      1 |      8 |
| 4      |      1 |      9 |
| 5      |      1 |     10 |
+--------+--------+--------+

伪码

依次用col1_B替换/更新Col3_A。

我的代码:不起作用,因为我的代码使用随机值更新Col3_A

Update A
Set col2_A = '1', col3_A = (select col1_B from B)

我需要使用光标吗?请帮忙

2 个答案:

答案 0 :(得分:2)

试试这个:

DECLARE @t1 TABLE ( id INT, col1 INT, col2 INT );

DECLARE @t2 TABLE ( id INT, col1 INT );

INSERT  INTO @t1
VALUES  ( 1, 3, 5 ),
        ( 2, 3, 3 ),
        ( 3, 3, 2 ),
        ( 4, 3, 1 ),
        ( 5, 3, 8 );

INSERT  INTO @t2
VALUES  ( 11, 6 ),
        ( 12, 7 ),
        ( 13, 8 ),
        ( 14, 9 ),
        ( 15, 10 );


UPDATE  l
SET     l.col1 = '1', l.col2 = r.col1
FROM    ( SELECT    ROW_NUMBER() OVER ( ORDER BY id ) row ,
                    *
          FROM      @t1
        ) AS l
        INNER JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY id ) row ,
                            *
                     FROM   @t2
                   ) AS r ON r.row = l.row
WHERE   r.row = l.row;

SELECT  *
FROM    @t1;

结果:

enter image description here

答案 1 :(得分:0)

这是你想要的吗?

update A, B set col2_A = 1, A.col3_A = B.Col1_B where A.Id = B.Id;

编辑1

好的,然后添加伪id,并在更新后删除它。

alter table A add column id1 int;
set @n = 0;
update A set id1 = @n := @n+1;
update A, (select @n := @n + 1 id, col1_B from B, (SELECT @n := 0) m) b set A.col3_A = b.col1_B where A.id1 = b.id;
alter table A drop column id1;