【问题标题】:Stored procedure NULL values SQL Server存储过程 NULL 值 SQL Server
【发布时间】:2016-03-21 17:16:01
【问题描述】:

我有一个存储过程,它从视图中选择数据并根据条件将其插入tempTable。我要做的是确保如果添加日期有 NULL 值,它们会被排除在外。

Insert into tempIntake(Pop, PlanID, PopFull, ApptDate, 1stAppt, Followup, Rn, UserID)
select Pop, PlanID, PopFull, InterviewDate, 1stAppt, Followup, rn, @UserID 
from 
   (Select *, row_number() over (partition by PlanID order BY AddedDate ASC) as rn 
     from VInfo) t
where rn = 1 
and interviewdate >= @fromDate 
and interviewDate <= @toDate

我该怎么做?

我基本上是在尝试按较早的 ADDEDDATE 进行过滤,但排除可能出现的 NULL 日期。

我有这个 SP,而且我还有另一个执行 ADDEDDATE DESC 的存储过程。但我不知道这是否喜欢我只有一次约会的事实。对于 ASC 分区,它提取一个空值,对于 DESC,它提取一个实际日期(只有一个日期)。我希望能够在两个存储过程中使用该日期(除非有多个日期 - 那是我希望它获取最早日期和最晚日期的时间)

【问题讨论】:

    标签: sql-server stored-procedures null


    【解决方案1】:

    除非我遗漏了什么,派生表中的一个简单的 where 子句应该可以解决问题:

    Insert into tempIntake(Pop, PlanID, PopFull, ApptDate, 1stAppt, Followup, Rn, UserID)
    select Pop,PlanID, PopFull,InterviewDate,1stAppt,Followup, rn, @UserID 
    from (
        Select *,row_number() over (partition by PlanID order BY AddedDate ASC) as rn 
        from VInfo
        where AddedDate is not null 
    ) t
    where rn = 1 
    and interviewdate >=@fromDate 
    and interviewDate <=@toDate
    

    更新

    根据我们在 cmets 中的对话,我认为您正在寻找这样的东西:

    Insert into tempIntake(Pop, PlanID, PopFull, ApptDate, 1stAppt, Followup, Rn, UserID)
    select Pop,PlanID, PopFull,InterviewDate,1stAppt,Followup, rn, @UserID 
    from (
        Select *,row_number() over (partition by PlanID order BY AddedDate ASC) as rn 
        from VInfo
        where AddedDate is not null 
    ) t
    where rn = 1 
    and interviewdate >=@fromDate 
    and interviewDate <=@toDate
    
    union 
    
    select Pop,PlanID, PopFull,InterviewDate,'2016-01-01',Followup, rn, @UserID 
    from (
        Select *,row_number() over (partition by PlanID order BY AddedDate ASC) as rn 
        from VInfo t1
        where AddedDate is null 
        and not exists 
        (
            select 1
            from VInfo t
            where AddedDate is not null 
            and interviewdate >=@fromDate 
            and interviewDate <=@toDate
        )
    ) t
    where rn = 1 
    and interviewdate >=@fromDate 
    and interviewDate <=@toDate
    

    【讨论】:

    • 您用分区编辑的内容是否足以让我在最早日期之前提取数据,其中日期不为空???
    • row_number() 是用select 子句计算的,所以它只计算被where 子句过滤后的行。
    • 对于 PlanID - 在某些情况下,有时我有多个日期,但有时我也只有一个日期,其他值为 NULL。为什么当我只有一个日期并运行我所包含的 SP 时,当我按 AdditionalDate ASC 按 PlanID 顺序进行分区时,我提取了 NULL 值,但是,当我这样做时……按 PlanID 顺序分区AdditionalDate Desc 我得到了日期。我希望能够在这两种情况下使用日期。出于某种原因,当我包含添加日期不为空的位置时 - 我没有获得所有数据(我猜某些 PlanID 没有添加日期)
    • 我不明白您在此评论中的要求。
    • 我是否可以指定 IF addedDate 为空,然后将其设为 2016 年 1 月 1 日 - 或者在这种情况下,我想说如果 ADDEDdate 为空,那么 2016 年 1 月 1 日和 1stAppt = NULL
    猜你喜欢
    • 2010-11-23
    • 1970-01-01
    • 2015-11-12
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多