我的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
答案 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