Update one by one records using loop in SQL Server

大憨熊 提交于 2019-12-13 03:34:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!