It took me an afternoon to finally understand the stored procedure and cursor. I only passed the code and did not speak. For more information about the stored procedure and cursor writing, please leave a message.
1 -- create the storage process sp_tittles
2 If exists (select * From SYS. objects where type = 'p' and name = 'SP _ titles ')
3 drop proc sp_titles
4 go
5 create proc sp_titles
6
7 declare @ problemid int, @ titleid int, @ item int
8 -- declare a cursor
9 declare cursor_title cursor
10 select [pid], [ID]
11 from [tb_titles]
12 -- open the cursor
13 open cursor_title
14 -- extract the first row of the cursor
15 fetch next from cursor_title into @ problemid, @ titleid
16 -- cyclically extract cursor content
17 while @ fetch_status = 0
18 begin
19 if exists (
20 select *
21 from [tb_problemindex]
22 where [problemid] = @ problemid)
23 begin
24 select top 1 @ item = [ID] from [tb_titles] Where [pid] = @ problemid order by createtime DESC
25 update [tb_problemindex] Set [titleid] = @ item where [problemid] = @ problemid
26 end
27 else
28 insert into [tb_problemindex] ([problemid], [titleid])
29 values (@ problemid, @ titleid)
30 fetch next from cursor_title into @ problemid, @ titleid
31 end
32 -- close the cursor
33 close cursor_title
34 -- release cursor Resources
35 deallocate cursor_title
36 go
37 -- storage process sp_titles ended
38
39 -- execute the Stored Procedure sp_titles
40 exec sp_titles
41
42 -- create a stored procedure sp_answers
43 if exists (select * From SYS. objects where type = 'p' and name = 'SP _ answers ')
44 drop proc sp_answers
45 go
46 create proc sp_answers
47
48 declare @ problemid int, @ answerid int
49 -- declare a cursor
50 declare cursor_answer cursor
51 select [pid], [ID]
52 from [tb_answers]
53 -- open the cursor
54 open cursor_answer
55 -- extract the content of the first row of the cursor
56 fetch next from cursor_answer into @ problemid, @ answerid
57 -- cyclically extract cursor content
58 While @ fetch_status = 0
59 begin
60 update [tb_problemindex] Set [answerid] = @ answerid where [problemid] = @ problemid
61 fetch next from cursor_answer into @ problemid, @ answerid
62 end
63 -- close the cursor
64 close cursor_answer
65 -- release cursor Resources
66 deallocate cursor_answer
67 go
68 -- storage process sp_answers ends
69
70 -- execute the Stored Procedure sp_answers
71 exec sp_answers