How to embed and if statement inside a case. This is what I have so far.
DECLARE @LDCCode as int
DECLARE @InvoiceDate as datetime
DECLARE @PaymentSemiMonthlyDays AS int
SET @LDCCode = 20
SET @InvoiceDate = '5/16/2012'
DECLARE @InvDateDayMonth AS INT
DECLARE @ReturnDate AS DATETIME
SET @ReturnDate = @InvoiceDate
DECLARE @PaymentDOM AS INT
DECLARE @PaymentDays AS INT
DECLARE @PaymentSemiMonthlyOffset AS INT
SET @ReturnDate = CASE WHEN NOT @PaymentDOM IS NULL THEN
@ReturnDate + (@PaymentDOM - DATEPART(day, DateAdd(mm,1,@ReturnDate)))
WHEN NOT @PaymentDays IS NULL THEN
DATEADD(Day,@PaymentDays,@ReturnDate)
WHEN NOT @PaymentSemiMonthlyOffset IS NULL THEN
IF @LDCCode = 40 AND @InvDateDayMonth > 11 AND @InvDateDayMonth < 26
SELECT @ReturnDate + (@PaymentSemiMonthlyOffset - DATEPART(day, DateAdd(mm,1,@ReturnDate)))
ELSE
SELECT @ReturnDate + (@PaymentSemiMonthlyDays - DATEPART(day, DateAdd(mm,1,@ReturnDate)))
END
The short answer is yes, you can nest an if inside of swtich / case statement (or vice versa).
SQL Server CASE statement is equivalent to the IF-THEN statement in Excel. The CASE statement is used to implement the logic where you want to set the value of one column depending upon the values in other columns. The SQL Server CASE Statement consists of at least one pair of WHEN and THEN statements.
In the Nested CASE expression, the outer statement executes until satisfying a condition. Once the condition is met, the inner CASE expression executes and returns a single result. If no condition is met in the outer statement, CASE expression returns the value in the ELSE statement.
You can't combine logic in that manner, but you can add a nested CASE
your existing CASE
statement:
SET @ReturnDate = (CASE WHEN NOT @PaymentDOM IS NULL THEN
@ReturnDate + (@PaymentDOM - DATEPART(day, DateAdd(mm,1,@ReturnDate)))
WHEN NOT @PaymentDays IS NULL THEN
DATEADD(Day,@PaymentDays,@ReturnDate)
WHEN NOT @PaymentSemiMonthlyOffset IS NULL THEN
CASE WHEN @LDCCode = 40 AND @InvDateDayMonth > 11 AND @InvDateDayMonth < 26 THEN
@ReturnDate + (@PaymentSemiMonthlyOffset - DATEPART(day, DateAdd(mm,1,@ReturnDate)))
ELSE
@ReturnDate + (@PaymentSemiMonthlyDays - DATEPART(day, DateAdd(mm,1,@ReturnDate)))
END
END)
Though, if this is in a stored procedure, I might just opt for simpler IF/THEN/ELSE
structure instead of the CASE
:
IF @PaymentDOM IS NULL
SET @ReturnDate = @ReturnDate + (@PaymentDOM - DATEPART(day, DateAdd(mm, 1, @ReturnDate)))
ELSE IF NOT @PaymentDays IS NULL
SET @ReturnDate = DATEADD(Day,@PaymentDays,@ReturnDate)
ELSE IF NOT @PaymentSemiMonthlyOffset IS NULL
BEGIN
IF @LDCCode = 40 AND @InvDateDayMonth > 11 AND @InvDateDayMonth < 26
SET @ReturnDate = @ReturnDate + (@PaymentSemiMonthlyOffset - DATEPART(day, DateAdd(mm, 1, @ReturnDate)))
ELSE
SET @ReturnDate = @ReturnDate + (@PaymentSemiMonthlyDays - DATEPART(day, DateAdd(mm, 1, @ReturnDate)))
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With