Microsoft SQL Server:使用组合值更新多个行,并将它们与另一个表中的值进行比较

时间:2016-08-11 13:22:11

标签: sql-server tsql

我的SQL Server数据库中有两个表。

表1如下所示:

Material   Semifinished     Number
-----------------------------------
Steel      Flat 1x2
Iron       Round 100x200

表2如下所示:

Material   Semifinished     Number
-----------------------------------
Steel      Flat 1x2         8991
Iron       Round 100x200    1234

现在我想将表2中的列Number的值插入表1中的列Number。其标准应该是列Material和列的组合Semifinished

我之前尝试过这个:

update T1
set T1.NUMBER = T2.NUMBER
from TABLE1 AS T1 
inner join TABLE2 AS T2 on T1.MATERIAL + T1.SEMIFINISHED = T2.MATERIAL + T2.SEMIFINISHED
where T1.MATERIAL + T1.SEMIFINISHED = T2.MATERIAL + T2.SEMIFINISHED

我也试过这个:

ALTER TABLE TABLE1 ADD [NEWCOL] varchar(100)
ALTER TABLE TABLE2 ADD [NEWCOL] varchar(100)

update TABLE1 
set NEWCOL = MATERIAL + SEMIFINISHED 

update TABLE2 
set NEWCOL = MATERIAL + SEMIFINISHED

update T1
set T1.NUMBER = T2.NUMBER
from TABLE1 AS T1 
inner join TABLE2 AS T2 on T1.NEWCOL = T2.NEWCOL
where T1.NEWCOL = T2.NEWCOL

3 个答案:

答案 0 :(得分:1)

您的错误无法重现。

这对我有用:

DECLARE @Table1 TABLE (
  Material varchar(255)
, Semifinished varchar(255)
, Number int
);

DECLARE @Table2 TABLE (
  Material varchar(255)
, Semifinished varchar(255)
, Number int
);

INSERT INTO @Table1
VALUES ('Steel','Flat 1x2',NULL),('Iron','Round 100x200',NULL);

INSERT INTO @Table2
VALUES ('Steel','Flat 1x2',8991),('Iron','Round 100x200',1234);

update T1
set T1.NUMBER = T2.NUMBER
from @Table1 AS T1 
inner join @Table2 AS T2 on T1.MATERIAL + T1.SEMIFINISHED = T2.MATERIAL + T2.SEMIFINISHED
where T1.MATERIAL + T1.SEMIFINISHED = T2.MATERIAL + T2.SEMIFINISHED

SELECT * FROM @Table1

结果:

Material    Semifinished    Number
Steel       Flat 1x2        8991
Iron        Round 100x200   1234

答案 1 :(得分:0)

感谢您的帮助,但我找到了解决方案。

我改变了最后一部分:

update TABLE1
set NUMBER = T2.NUMBER
from TABLE1 AS T1 
inner join TABLE2 AS T2 on T1.NEWCOL = T2.NEWCOL

答案 2 :(得分:0)

工作正常

DECLARE @T1 TABLE(
    Material NVARCHAR(200),
    Semifinished NVARCHAR(200),
    Number INT
)

DECLARE @T2 TABLE(
    Material NVARCHAR(200),
    Semifinished NVARCHAR(200),
    Number INT
)

INSERT INTO @T1 SELECT 'Steel','Flat 1x2',NULL
INSERT INTO @T1 SELECT 'Iron','Round 100x200',NULL

INSERT INTO @T2 SELECT 'Steel','Flat 1x2',8991
INSERT INTO @T2 SELECT 'Iron','Round 100x200',1234

update T1
set T1.NUMBER = T2.NUMBER
from @T1 AS T1 
inner join @T2 AS T2 on T1.MATERIAL = T2.MATERIAL AND
    T1.SEMIFINISHED = T2.SEMIFINISHED

SELECT * FROM @T1
SELECT * FROM @T2