简体   繁体   English

IF ELSE 在 SQL 服务器中返回错误值

[英]IF ELSE return wrong value in SQL Server

I have a script that need to return the DATETIME from IF ELSE condition.我有一个脚本需要从 IF ELSE 条件返回 DATETIME。 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开始日期 = 2020 年 12 月 1 日上午 12:00
  • end_date = May 31 2021 12:00AM end_date = 2021 年 5 月 31 日上午 12:00

but it only return value但它只返回值

  • begin_date = Dec 1 2020 12:00AM开始日期 = 2020 年 12 月 1 日上午 12:00

But from that script why it entered to ELSE condition @initial_date ?但是从那个脚本为什么它进入 ELSE 条件@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 .如果我正确理解你的问题,这个意外结果的原因是最后一行( SET @end_date = DATEADD(MONTH, DATEDIFF(MONTH, 0, @begin_date) + @datediff, DATEPART(d, @initial_date)); )位于IF.. ELSE块之外,并且始终将NULL @end_date Probably an appropriate BEIGN.. END block in the last IF..ELSE statement will solve this issue:最后一个IF..ELSE语句中的适当BEIGN.. END块可能会解决此问题:

...
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    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM