Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple SQL Update Statements in single query

Tags:

sql

sql-update

I am in a situation where I am having to update about 12,000 items in my DB. Each row needs to mirror an excel file that I made previously. I have made the file that creates each line of SQL statement, but I am not sure if I can run each line in a single query.

This is an example of what I am trying to do.

UPDATE [STORESQL].[dbo].[RPT_ITM_D] SET F1301='1.29' WHERE F01='0000000000001'
UPDATE [STORESQL].[dbo].[RPT_ITM_D] SET F1301='1.39' WHERE F01='0000000000002'

Will this work, or are there any better options for what I am trying to achieve?

Each item will have a unique value and the column to be changed will have a unique value as well. I don't see how I could make this work with a loop, or any other methods I've found so far. I realize that this might take a long time to process, but time is not an issue.

Thank you in advance

like image 776
Erick Ely Avatar asked Feb 06 '12 15:02

Erick Ely


People also ask

Can we run multiple UPDATE statements in SQL?

Yes, you could add all the single-line-Update-statements in one query like you are doing.

How do you write multiple UPDATE statements?

One way to update multiple rows is to write multiple UPDATE statements. They can be separated with a semicolon (;) and submitted as a group (called a batch).

Can we UPDATE multiple rows in a single SQL statement?

Column values on multiple rows can be updated in a single UPDATE statement if the condition specified in WHERE clause matches multiple rows. In this case, the SET clause will be applied to all the matched rows.


2 Answers

Something like this is the best you can do:-

UPDATE [STORESQL].[dbo].[RPT_ITM_D] 
SET   F1301 = 
      case  F01 
      when '0000000000001' then '1.29'
      when '0000000000002' then '1.30'
      ELSE F1301

end

Other than that, running multiple updates is the way to go.

like image 73
Icarus Avatar answered Oct 17 '22 08:10

Icarus


Yes, you could add all the single-line-Update-statements in one query like you are doing.

like image 45
Bassam Mehanni Avatar answered Oct 17 '22 09:10

Bassam Mehanni