我正在使用SQL Server2008。我有2个表Table1
和Table2
。
Table1
具有列
SchoolCode, District, Type, SchoolName
和Table2
的列
SchoolCode1, District1, Type1, SchoolName1
两个表中的 SchoolCode
列具有相同的代码,例如“ 1234”; schoolcode
列中的代码都相同。
现在,如果两个表中的District
都为Type
,则我想将SchoolName
的{{1}},Table1
和Table2
列值从SchoolCode
复制到filling_values=0
一样。
我认为查询将使用联接,但是我不知道它是如何工作的。对我如何执行此任务有帮助吗?
答案 0 :(得分:1)
如果在复制时表示要更新行,则可以在连接中使用update语句
update t2
set
District1= District,
Type1= Type,
SchoolName1= SchoolName
from Table1 t1
join
Table2 t2
on t1.SchoolCode=t2.SchoolCode1
答案 1 :(得分:1)
我可以给你一点点想法。在这里:
Insert into table2 (District1, Type1, SchoolName1)
SELECT District, Type, SchoolName
FROM table1
where table1.Schoolcode=table2.Schoolcode1
答案 2 :(得分:1)
您必须使用内部联接将表1中的数据更新到表2,内部联接将联接相等的值。 。要了解有关联接的更多信息,强烈建议您阅读以下文章
SQLServer Joins Explained - W3Schools
为方便起见,请使用下面的代码。.
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
答案 3 :(得分:0)
您可以在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