I have a script that need to return the DATETIME from IF ELSE condition. But my return value from this got a wrong value here.
So this is my script
DECLARE @last_date SMALLDATETIME;
DECLARE @end_date SMALLDATETIME;
DECLARE @initial_date SMALLDATETIME;
DECLARE @begin_date SMALLDATETIME;
DECLARE @datediff int;
DECLARE @date_day int;
SET @last_date = NULL;
SET @datediff = NULL;
SET @initial_date = NULL;
IF (@datediff = '' or @datediff is NULL)
SET @datediff = 5;
ELSE
SET @datediff = @datediff;
IF (@last_date = '' or @last_date is NULL)
SET @end_date = DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1);
ELSE
SET @end_date = DATEADD(MONTH, DATEDIFF(MONTH, -1, @last_date)-1, -1);
IF (@initial_date = '' or @initial_date is NULL)
SET @begin_date = DATEADD(MONTH, DATEDIFF(MONTH, 0, @end_date)-@datediff, 0);
ELSE
SET @begin_date = @initial_date;
SET @end_date = DATEADD(MONTH, DATEDIFF(MONTH, 0, @begin_date)+@datediff, DATEPART(d,@initial_date));
print(@begin_date)
print(@end_date)
From this logic, it should take a value like this
but it only return value
But from that script why it entered to ELSE condition @initial_date
? is there any something wrong from my script?
If I understand your issue correctly, the reason for this unexpected result is that the last line ( SET @end_date = DATEADD(MONTH, DATEDIFF(MONTH, 0, @begin_date) + @datediff, DATEPART(d, @initial_date));
) is outside the IF.. ELSE
block and always sets the value of @end_date
to NULL
. Probably an appropriate BEIGN.. END
block in the last IF..ELSE
statement will solve this issue:
...
IF (@initial_date = '' or @initial_date is NULL)
SET @begin_date = DATEADD(MONTH, DATEDIFF(MONTH, 0, @end_date)-@datediff, 0);
ELSE BEGIN
SET @begin_date = @initial_date;
SET @end_date = DATEADD(MONTH, DATEDIFF(MONTH, 0, @begin_date)+@datediff, DATEPART(d,@initial_date));
END
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.