在 SQL Server 中使用循环更新一条记录 [英] Update one by one records using loop in SQL Server
本文介绍了在 SQL Server 中使用循环更新一条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有扇区 ID,需要使用循环将每个扇区 ID 的扇区名称和扇区短名称分别更新为扇区 1"和扇区 1".我怎样才能做到这一点?
I have Sector ID, need to update sector name and sector short name as 'Sector 1' and 'Sector 1' for each sector id respectively using loop. How can I achieve this?
SectorID SectorName SectorShortName
---------------------------------------
1 METALS METAL
2 FINANCIAL SERVICES FINAN
3 IT IT
4 SERVICES SERVI
5 PHARMA PHARM
6 CHEMICALS CHEMI
7 TEXTILES TEXTI
8 ENERGY ENERG
9 INDUSTRIAL MANUFACTURING INDUS
10 CEMENT & CEMENT PRODUCTS CEMEN
11 CONSUMER GOODS CONSU
12 CONSTRUCTION CONST
13 TELECOM TELEC
14 AUTOMOBILE AUTOM
15 HEALTHCARE SERVICES HEALT
16 FERTILISERS & PESTICIDES FERTI
17 MEDIA & ENTERTAINMENT MEDIA
18 PAPER PAPER
19 PENDING UPDATION PENDING
20 OTHERS OTHERS
21 FINANCIAL SERVICES - HFC (AA and Above) FS-HFC-AA
22 Scheduled Commercial Bank SCB
23 FINANCIAL SERVICES - PSU, PFI (AAA) PSUPFIAAA
24 NO NO
25 YES YES
26 FINANCIAL SERVICES - HFC (Below AA) FSHFC<AA
27 Other than PSU, PFI & PSB Limit Appl
28 PSU PSU
29 PSB PSB
30 PFI PFI
31 SOVEREIGN SOVEREIGN
推荐答案
您只需使用 update
:
update sectors
set SectorName = replace('sector [n]', '[n]', id),
SectorShortName = replace('sector [n]', '[n]', id);
绝对没有理由为此使用循环.或者更具体地说,update
使用基于集合的操作覆盖表中的所有行,因此效率更高,代码更短.
There is absolutely no reason to be using a loop for this. Or more specifically, update
covers all the rows in the table using set-based operations, so it is more efficient and the code is shorter.
这篇关于在 SQL Server 中使用循环更新一条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文