如何知道如果我的变量datetime是空的



我试图比较如果我的变量datetime是NULL,但它不起作用,我是新的在SQL中进行比较,所以可能有人说我怎么是好方法。这是我的代码:

declare @FechaInicial datetime 
set @FechaInicial = (select FecharIncialDescarga 
                     from Contenedores where Id_Contenedor=@IdContenedor)
if(@FechaInicial = NULL) ---
    begin
    end

你的问题的直接答案是is null:

if (@FechaInicial IS NULL)

这是因为几乎任何与NULL的比较都返回NULL,而NULL被视为假。

然而,我想指出的是,你可能真的想要这样的逻辑:

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

虽然将值赋给一个变量并检查NULL没有错,但这样更清晰,更有效。

您可以尝试使用if(@FechaInicial IS NULL),如下所示。

declare @FechaInicial datetime 
set @FechaInicial = (select FecharIncialDescarga from Contenedores 
                     where Id_Contenedor=@IdContenedor)
if(@FechaInicial IS NULL) ---
    begin
    end

如果你想检查NULLempty,你可以试试if(ISNULL(@FechaInicial, '') = ''),如下所示。

declare @FechaInicial datetime 
set @FechaInicial = (select FecharIncialDescarga 
                     from Contenedores where Id_Contenedor=@IdContenedor)
if(ISNULL(@FechaInicial, '') = '') ---
    begin
    end

也是一个recommendation,而不是上面使用的SET,你可以用SELECT

像下面这样重构它
SELECT @FechaInicial = FecharIncialDescarga 
FROM Contenedores WHERE Id_Contenedor = @IdContenedor

最新更新