SQL Server How to run stored procedure for every row on table?

gblwokeq  于 2023-02-28  发布在  其他
关注(0)|答案(1)|浏览(168)

I have a stored procedure that accepts the following parameters

@Company_Move_From INT = NULL,
@Company_Move_To INT = NULL

I then have a table of data that looks like the below. This is my reference table which tells me which OldCompanyIDs need to be updated to the NewCompanyID .

OldCompanyID       NewCompanyID
-------------------------------
  11112               23847
  11113               23433
  11114               24652

Then I have my CompanyTable :

CompanyID        CompanyName
 ----------------------------- 
   11112              TEST1
   11113              TEST2
   11114              TEST3

The stored procedure basically just updates the record on a company table. It will look for all records that match @Company_Move_From and update them to @Company_Move_To .

What would be the best way to run this stored procedure for each row of my reference table above? I researched and found cursor suggestions but my understanding was that cursors can perform badly and best to avoid..

The stored procedure works fine, it's just getting it to run for every row on my reference table I am struggling with.

Any other suggestions on the most efficient way to run this?

x6492ojm

x6492ojm1#

Why do you need a stored procedure? This SQL statement should do the update for you:

UPDATE Company
SET CompanyID  = NewCompanyID
FROM Company, ReferenceTable
WHERE Company.CompanyID = ReferenceTable.OldCompanyID;

相关问题