Search code examples
sqlsql-serverdatediff

DATEDIFF function on SQL server returns a null value when I use variables


I am trying to get the total of minutes between a start time and end time. This data is found on the same table, same column and I have set a variable to return the values I need.

So far, that is working fine. Now, the problem comes when I use DATEDIFF with the variables as it returns NULL:

DECLARE @hol datetime

SET @hol = (
    SELECT fecha_Registro  
    FROM Registro  
    WHERE id_Registro = 4  
        AND id_Tipo_Registro = 2
);  

SELECT @hol as varText 

DECLARE @bye DATETIME 

SET @hol = (
    SELECT fecha_Registro  
    FROM Registro  
    WHERE id_Registro = 3  
        AND id_Tipo_Registro = 1
);  

SELECT @hol as varText2  

SELECT DATEDIFF(MI, @bye, @hol) as total_minutos 

As you can see the variables have the correct values on them, so, I am not understanding why does it comes back null. When I do it with the actual dates, it works fine.


Solution

  • You declare @bye variable, which isn't assigned anywhere. So it gets NULL default value, so DATEDIFF(MI, @bye, @hol) evalutes to null as well.

    One more possibility is that query

    select fecha_Registro  
    from Registro  
    where id_Registro = 3  
    and id_Tipo_Registro = 1
    

    returns NULL.