ruedi
ruedi

Reputation: 5555

IF/ELSE-IF depending on quarter doesnt work for the last quarter

I have a statement that sums entries for every quarter of the year.

BEGIN
SET @mth = DATEPART(MONTH, GETDATE())
IF @mth BETWEEN '1' AND '3'
-- SELECT-Statement
ELSE IF @mth BETWEEN '4' AND '6'
-- SELECT-Statement
ELSE IF @mth BETWEEN '7' AND '9'
-- SELECT-Statement
ELSE IF @mth BETWEEN '10' AND '12'
-- SELECT-Statement
END

Till yesterday the Select-Statement works fine and sums what i want, today it doenst work anymore. I tired the select statement separately and it works and gives me the correct result. I also tried to change "ELSE IF @mth BETWEEN '10' AND '12'" to "ELSE" in the line of '10' AND '12', no help. The debugger doesnt even stop if i set a breakpoint in front of the last select statement. Anyone an idea where the problem is?

Upvotes: 0

Views: 70

Answers (3)

t-clausen.dk
t-clausen.dk

Reputation: 44336

This is how you could have solved it:

DECLARE @from datetime 
SET @from = dateadd(month, datediff(month, 0, current_timestamp)/3*3, 0)
-- SELECT-Statement....
-- WHERE datefield >= @from
-- AND datefield < dateadd(month, 3, @from)

Upvotes: 0

Nitu Bansal
Nitu Bansal

Reputation: 3856

it may be the reason that you have declare @mth as varchar,

define it as int

Upvotes: 0

Sachin
Sachin

Reputation: 40970

I guess that you probably Declared a @mth variable as varchar that can cause the issue. If you declared it as int, you will get your expected result.

BEGIN
DECLARE @mth int
SET @mth = DATEPART(MONTH, GETDATE())
IF @mth BETWEEN '1' AND '3'
print '1'
-- SELECT-Statement
ELSE IF @mth BETWEEN '4' AND '6'
print '2'
-- SELECT-Statement
ELSE IF @mth BETWEEN '7' AND '9'
print '3'
-- SELECT-Statement
ELSE IF @mth BETWEEN '10' AND '12'
print '4'
-- SELECT-Statement
END

Upvotes: 2

Related Questions