1

I am attempting to put an IF ELSE statement into the follow SQL Query, but it keeps breaking when I try to execute. I have never used IF ELSE in SQL so I am assuming I am not including it correctly

Query without IF ELSE

UPDATE RA SET 
CreditInvoiceAmount = CSV.CreditInvoiceAmount, 
CreditInvoiceDate = CSV.CreditInvoiceDate, 
CreditInvoiceNumber = CSV.CreditInvoiceNumber, 
CreditDeniedDate = CSV.CreditDeniedDate, 
CreditDeniedReasonId = CSV.CreditDeniedReasonId, 
CreditDeniedNotes = CSV.CreditDeniedNotes 
FROM ReturnAuthorization RA 
JOIN TemporaryCsvUpload CSV 
on RA.Id = CSV.Id

IF ELSE

IF CSV.CreditInvoiceDate = null AND CSV.CreditDeniedDate != null THEN
StatusId = 7;
ELSE
StatusId = 8;

Insert Attempt

UPDATE RA SET 
CreditInvoiceAmount = CSV.CreditInvoiceAmount, 
CreditInvoiceDate = CSV.CreditInvoiceDate, 
CreditInvoiceNumber = CSV.CreditInvoiceNumber, 
CreditDeniedDate = CSV.CreditDeniedDate, 
CreditDeniedReasonId = CSV.CreditDeniedReasonId, 
CreditDeniedNotes = CSV.CreditDeniedNotes,
IF CSV.CreditInvoiceDate = null AND CSV.CreditDeniedDate != null THEN
StatusId = 7;
ELSE
StatusId = 8; 
FROM ReturnAuthorization RA 
JOIN TemporaryCsvUpload CSV 
on RA.Id = CSV.Id

Any guidance on how to correctly put this if statement into the SQL block would be appreciated. Thanks!

2 Answers 2

1

Use a CASE expression to implement a IF logic based on which you determine what value to assign into a column for a specific row.

UPDATE RA
SET CreditInvoiceAmount = CSV.CreditInvoiceAmount
    ,CreditInvoiceDate = CSV.CreditInvoiceDate
    ,CreditInvoiceNumber = CSV.CreditInvoiceNumber
    ,CreditDeniedDate = CSV.CreditDeniedDate
    ,CreditDeniedReasonId = CSV.CreditDeniedReasonId
    ,CreditDeniedNotes = CSV.CreditDeniedNotes
    ,StatusId = CASE 
                    WHEN CSV.CreditInvoiceDate IS NULL
                        AND CSV.CreditDeniedDate IS NOT NULL
                            THEN 7
                    ELSE 8
                END
FROM ReturnAuthorization RA
INNER JOIN TemporaryCsvUpload CSV ON RA.Id = CSV.Id

CASE is valid for both SQL Server and MySQL, so it should work with either systems. Also, please consider editing your question and leaving only the relevant tag (what RDBMS you're actually using).

Sign up to request clarification or add additional context in comments.

Comments

0

// You can try this

StatusId = IF ((CSV.CreditInvoiceDate IS NULL AND CSV.CreditDeniedDate IS NOT NULL), 7, 8)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.