存储过程NULL值SQL Server

时间:2016-03-21 17:16:01

标签: sql-server stored-procedures null

我有一个存储过程,可以从视图中选择数据,并根据条件将其插入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,它会拉出一个实际日期(只有一个日期)。我希望能够在两个存储过程中使用该日期(除非有多个日期 - 我希望它能抓住最早的日期和最新日期)

1 个答案:

答案 0 :(得分:2)

除非我遗漏了某些内容,派生表中的简单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

<强>更新

按照我们在评论中的对话,我认为这就是你要找的东西:

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