Update Fields When Do Not Exist

Johnathan Simpson 586 Reputation points
2020-10-16T17:05:47.78+00:00

I have the below DDL - everything works great when the order number exists in both tables, however, I need to update ccCardCapture to either Yes/No. I've been doing it with two seperate update queries, but can this be combined to ONE update query?

    Declare @Info Table
    (
        ordernumber varchar(100)
        ,ccCardCapture varchar(10)
        ,ccAuthAmount decimal(16,4)
        ,ccCollectAmount decimal(16,4)
    )


    Declare @Payment Table
    (
        ordernumber varchar(100)
        ,CardCaptured varchar(10)
        ,AuthAmount decimal(16,4)
        ,CollectedAmount decimal(16,4)
    )


    Insert Into @Info (ordernumber) Values
    ('abc123'), ('def456'), ('ghi789'), ('jkl000'), ('mno000')

    Insert Into @Payment (ordernumber, CardCaptured, AuthAmount, CollectedAmount) Values
    ('jkl000', 'Yes', 26.12, 26.12), ('mno000', 'Yes', 11.11, 11.11)


    Update t1
    Set t1.ccAuthAmount = pa.authamount
    ,t1.ccCollectAmount = pa.collectedamount
    ,t1.ccCardCapture = pa.CardCaptured
    FROM @Info t1
    Join @Payment pa
    ON t1.ordernumber = pa.ordernumber

    UPDATE @Info 
    SET ccCardCapture = 'No'
    Where ccCardCapture IS NULL

    Select * from @Info
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,690 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 120K Reputation points
    2020-10-16T17:17:52.093+00:00

    Try using LEFT JOIN and ISNULL:

    Update t1
    Set t1.ccAuthAmount = pa.authamount,
        t1.ccCollectAmount = pa.collectedamount,
        t1.ccCardCapture = isnull(pa.CardCaptured, 'No')
    FROM @Info t1
    left Join @Payment pa 
    ON t1.ordernumber = pa.ordernumber
    

    It also writes NULL to ccAuthAmount and ccCollectAmount, which is probably correct.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.