在 SQL 服务器中使用循环更新一条记录
Update one by one records using loop in SQL Server
我有扇区 ID,需要使用循环将每个扇区 ID 的扇区名称和扇区短名称分别更新为 'Sector 1' 和 'Sector 1'。我怎样才能做到这一点?
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
使用基于集合的操作覆盖 table 中的所有行,因此效率更高,代码更短。
我有扇区 ID,需要使用循环将每个扇区 ID 的扇区名称和扇区短名称分别更新为 'Sector 1' 和 'Sector 1'。我怎样才能做到这一点?
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
使用基于集合的操作覆盖 table 中的所有行,因此效率更高,代码更短。