mardi 15 juin 2021

IF ELSE return wrong value in SQL Server

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

  • begin_date = Dec 1 2020 12:00AM
  • end_date = May 31 2021 12:00AM

but it only return value

  • begin_date = Dec 1 2020 12:00AM

But from that script why it entered to ELSE condition @initial_date ? is there any something wrong from my script ?

Aucun commentaire:

Enregistrer un commentaire