问题
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
回答1:
You would simply use update
:
update sectors
set SectorName = replace('sector [n]', '[n]', id),
SectorShortName = replace('sector [n]', '[n]', id);
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.
来源:https://stackoverflow.com/questions/49952675/update-one-by-one-records-using-loop-in-sql-server