如何在SQL查询中包含IF ELSE

时间:2015-07-30 15:09:07

标签: sql-server

我正在尝试将IF ELSE语句放入后面的SQL Query中,但是当我尝试执行时它会不断破坏。我从来没有在SQL中使用IF ELSE,所以我假设我没有正确包含它

没有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;

插入尝试

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

有关如何将此if语句正确放入SQL块的任何指导将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:1)

使用CASE表达式实现IF逻辑,根据该逻辑确定要为特定行分配的值。

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对SQL Server和MySQL都有效,因此它适用于任一系统。另外,请考虑编辑您的问题,只留下相关标签(您实际使用的RDBMS)。

答案 1 :(得分:0)

//你可以尝试这个

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