Sql 匹配代码并复制列
我在SQLServer2008工作。我有两个表Sql 匹配代码并复制列,sql,sql-server,Sql,Sql Server,我在SQLServer2008工作。我有两个表Table1和Table2 表1有列 SchoolCode, District, Type, SchoolName SchoolCode1, District1, Type1, SchoolName1 并且表2有列 SchoolCode, District, Type, SchoolName SchoolCode1, District1, Type1, SchoolName1 SchoolCode两个表中的列具有相同的代码,如“1234”
Table1
和Table2
表1
有列
SchoolCode, District, Type, SchoolName
SchoolCode1, District1, Type1, SchoolName1
并且表2
有列
SchoolCode, District, Type, SchoolName
SchoolCode1, District1, Type1, SchoolName1
SchoolCode
两个表中的列具有相同的代码,如“1234”;两个schoolcode
列中的代码相同
现在,如果两个表中的学校代码
相同,我想将地区
、类型
和学校名称
列值从表1
复制到表2
我认为查询将使用join,但我不知道它是如何工作的。关于如何完成这项任务有什么帮助吗?如果复制是指更新行,那么可以在join中使用update语句
update t2
set
District1= District,
Type1= Type,
SchoolName1= SchoolName
from Table1 t1
join
Table2 t2
on t1.SchoolCode=t2.SchoolCode1
我可以给你一点建议。这是:
Insert into table2 (District1, Type1, SchoolName1)
SELECT District, Type, SchoolName
FROM table1
where table1.Schoolcode=table2.Schoolcode1
必须使用内部联接将数据从表1更新到表2,内部联接将联接相等的值。要了解更多关于连接的信息,我强烈建议您阅读下面的文章 为了方便我使用临时表,请参考以下代码
DECLARE @Table1 TABLE
(
SchoolCode INT,
District VARCHAR(MAX),
Type VARCHAR(MAX),
SchoolName VARCHAR(MAX)
)
DECLARE @Table2 TABLE
(
SchoolCode1 INT,
District1 VARCHAR(MAX),
Type1 VARCHAR(MAX),
SchoolName1 VARCHAR(MAX)
)
INSERT INTO @Table1
( SchoolCode ,District , Type , SchoolName
)
VALUES ( 1 ,'DIS1' ,'X' ,'A'),
( 2 ,'DIS2' ,'Y' ,'B'),
( 3 ,'DIS3' ,'Z' ,'C'),
( 4 ,'DIS4' ,'D' ,'D'),
( 5 ,'DIS5' ,'K' ,'E')
INSERT INTO @Table2
( SchoolCode1 ,District1 , Type1 , SchoolName1
)
VALUES ( 1 ,'DIS1' ,'X' ,'A'),
( 2 ,NULL ,'Z' ,NULL),
( 3 ,'DIS3' ,'Z' ,'C'),
( 4 ,NULL ,'Z' ,'S'),
( 5 ,'DIS5' ,'K' ,'E')
--BEFORE
SELECT * FROM @Table1
SELECT * FROM @Table2
--Logic UPDATE Table 2
UPDATE t2 SET t2.District1 = t1.District,
t2.Type1 = t1.Type,
t2.SchoolName1 = t1.SchoolName
FROM @Table1 t1
INNER JOIN @Table2 t2 ON t1.SchoolCode = t2.SchoolCode1
-- End Logic UPDATE Table 2
--AFTER
SELECT * FROM @Table1
SELECT * FROM @Table2
您可以在
UPDATE
语句中联接表
注意,我已将表、table1
和table2
分别命名为t1
和t2
这就是我所做的:
create table Table1
(SchoolCode varchar(50),
District varchar(50),[Type] varchar(50),SchoolName varchar(50))
go
create table Table2
(SchoolCode1 varchar(50), District1 varchar(50),[Type1] varchar(50),SchoolName1 varchar(50))
go
insert into table1 values ('1234','District1','High','Cool School')
insert into table1 values ('2222','District2','Lower','Leafy School')
insert into table2 (SchoolCode1) values ('1234')
go
update t2
set District1 = District,
Type1 = [Type],
SchoolName1 = SchoolName
from table1 t1
join table2 t2
on t2.SchoolCode1 = t1.SchoolCode
go
select * from table2
go
向我们展示您迄今为止所做的尝试-我们很乐意提供帮助-但我们不会只为您编写整个代码…..提示:一种方法是使用带有
内部联接的UPDATE
语句。