Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to merge multiple update queries into one query?

I need to update the description information for each province code in Provinces table. What I am doing is:

update Provinces
set Description='Mississippi'
where Code = 'MS'

update Provinces
set Description = 'Maryland'
where Code = 'MD'

.... --around 100 more update queries like that.

In this way, there is a repeated lines of code, which does not look good to me. I wonder if there is any better and more professional way to do the same task. Any help or advice would be appreciated.

like image 309
Eray Balkanli Avatar asked Aug 28 '17 12:08

Eray Balkanli


People also ask

How do I merge 3 queries in SQL?

If you want two more rows, then use UNION ALL. You still kind of have 3 queries but executed as one. If you want two more columns, then use SUM(CASE(...)). Basically you more your WHERE clause to the CASE clause 3 times each with own condition.

How do you update multiple values in one query?

just make a transaction statement, with multiple update statement and commit. In error case, you can just rollback modification handle by starting transaction.


2 Answers

An alternative to using case expression is to use a common table expression with a table value constructor and join to the cte like so:

;with ProvinceDescription as (
  select Description, Code
  from (values 
      ('Mississippi','MS')
     ,('Maryland','MD')
    ) v (Description, Code)
)
update p
  set p.Description = pd.Description
from Provinces p
  inner join ProvinceDescription pd
    on p.Code = pd.Code
where p.Description <> pd.Description;  
like image 43
SqlZim Avatar answered Oct 08 '22 23:10

SqlZim


You could use CASE:

update Provinces
set Description= CASE code WHEN 'MS' THEN 'Mississippi'
                           WHEN 'MD' THEN 'Maryland' 
                           -- ELSE 'some default value' --otherwise NULL
                 END
where Code IN('MS', 'MD');

Another approach is to create table variable and use UPDATE FROM JOIN syntax:

DECLARE @t AS (code VARCHAR(10), desc VARCHAR(1000));
INSERT INTO @t(code, desc) VALUES ('MS','Mississippi'), ('MD', 'Maryland');

UPDATE p
SET desc = t.desc
FROM Provinces p
JOIN @t t
  ON p.Code = t.code;
like image 58
Lukasz Szozda Avatar answered Oct 08 '22 22:10

Lukasz Szozda