Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

Update Query in SQL Server via JOINS

I have 2 tables as mentioned below

create table #temp(id int, userid int,age int) 

insert into #temp values (1,1,1)
insert into #temp values(2,1,2)
insert into #temp values(3,1,3)

create table #tempMOCK(id int, userid int,age int) 
insert into #tempMOCK values (6,1,7)
insert into #tempMOCK values (7,1,9)

I want to update the first 2 rows of Mock table on #temp table. I am expecting that age of rowids 2 & 3 should become 7 & 9. I'm using this query but somehow it doesn't work.

UPDATE t1
SET    t1.age = t2.age
FROM   #temp t1
INNER JOIN #tempMOCK t2 ON t1.userid = t2.userid where t1.id in (1,2)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since the user id is the same in all rows, you get the same value for the age.
This can be solved using a CTE, like this:

;with cte as 
(
  select id, userid, age, ROW_NUMBER() OVER(order by id) rn
  FROM #tempMock
)
UPDATE t1
SET    t1.age = t2.age
FROM   #temp t1
INNER JOIN cte t2 ON t1.userid = t2.userid and t1.id = t2.rn+1;

see fiddle here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...