Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,690 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
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.