-1

I'm trying to compare if my variable datetime is NULL, but it doesn't work, I'm new making comparising in SQL, so could someone said me how is the good way. This is my code:

declare @FechaInicial datetime 
set @FechaInicial = (select FecharIncialDescarga 
                     from Contenedores where Id_Contenedor=@IdContenedor)

if(@FechaInicial = NULL) ---
    begin
    end
Cœur
  • 37,241
  • 25
  • 195
  • 267
NAMH
  • 17
  • 1
  • 7

2 Answers2

3

The direct answer to your question is is null:

if (@FechaInicial IS NULL)

This is because almost any comparison to NULL returns NULL, and NULL is treated as false.

However, I want to point out that you might really intend this logic:

if (not exists (select 1 from Contenedores where Id_Contenedor = @IdContenedor))
begin 
    . . .
end;

Although there is nothing wrong with assigning the value to a variable and checking for NULL, this is clearer and can be more efficient.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

You can try this with if(@FechaInicial IS NULL) as below.

declare @FechaInicial datetime 
set @FechaInicial = (select FecharIncialDescarga from Contenedores 
                     where Id_Contenedor=@IdContenedor)

if(@FechaInicial IS NULL) ---
    begin
    end

If you want to check NULL and also empty, you can try if(ISNULL(@FechaInicial, '') = '') as below.

declare @FechaInicial datetime 
set @FechaInicial = (select FecharIncialDescarga 
                     from Contenedores where Id_Contenedor=@IdContenedor)

if(ISNULL(@FechaInicial, '') = '') ---
    begin
    end

Also a recommendation, Instead of a SET used above, you can refactor it as below with a SELECT

SELECT @FechaInicial = FecharIncialDescarga 
FROM Contenedores WHERE Id_Contenedor = @IdContenedor
SuicideSheep
  • 5,260
  • 19
  • 64
  • 117
Aruna
  • 11,959
  • 3
  • 28
  • 42