update table column based on sub table multiple value

kasim mohamed 581 Reputation points
2021-10-18T09:20:18.383+00:00

Hi,

I have a Main table and Sub table like below

create table Main (Code nvarchar(10), Amount decimal(18,2), NewAmount decimal(18,3))
create table Sub (Code nvarchar(10), Price decimal(18,2))

insert into Main values ('1111', 100,0)
insert into Sub values ('1111',10)
insert into Sub values ('1111',20)
insert into Sub values ('1111',100)

--update T Set T.NewAmount=0 from Main T inner join price P on T.code=P.Code
select * from Main
select * from Sub
drop table Main
drop table Sub

i need to update main table NewAmount column based on Sub table Price column

if Amount in Main table matched with price column in Sub Table then NewAmount in Main table should be Amount Value otherwise '0' value

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,710 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,552 questions
{count} votes

Accepted answer
  1. Viorel 112.1K Reputation points
    2021-10-18T11:17:41.907+00:00

    Check a possibility:

    update m
    set NewAmount = isnull(s.Price, 0)
    from Main m 
    left join Sub s on s.Code = m.Code and s.Price = m.Amount
    

    (If 's.Code = m.Code' is not needed, then remove it).

    Another possibility can be based on "CTE".

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. EchoLiu-MSFT 14,571 Reputation points
    2021-10-19T02:38:27.7+00:00

    Hi @kasim mohamed ,

    Please also check:

    update T   
    set T.NewAmount=case when Amount in(select Price from Sub P where T.code=P.Code)   
    then Amount else 0 end  
    from Main T   
    

    Or the cte mentioned by Viorel:

    ;With cte  
    as(select T.*,P.Price from Main T   
       left join Sub P on P.Code = T.Code and P.Price = T.Amount)  
      
    update Main  
    set NewAmount = isnull(Price, 0)  
    from cte  
    

    Output:
    141542-image.png

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.

    0 comments No comments