2016-03-21 34 views
0

我有一個存儲過程,從視圖中選擇數據並根據條件將其插入tempTable。我想要做的是確保如果有添加日期的NULL值,他們會被排除在外。存儲過程NULL值SQL Server

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過濾,但排除可能出現的空日期。

我有這個SP,我也有另一個存儲過程,做ADDEDDATE DESC。但我不知道這是否喜歡我只有一個約會的事實。對於ASC分區,它取出一個空值,對於DESC它取出一個實際日期(只有一個日期)。我希望能夠在這兩個存儲過程中使用該日期(除非有多個日期 - 這是當我希望它抓住最早的日期和最後的日期)

回答

2

除非我失去了一些東西,一個簡單的地方派生表條款應做的伎倆:

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 >[email protected] 
and interviewDate <[email protected] 

更新

繼我們在我認爲的意見談話像這是你在找什麼:

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 >[email protected] 
and interviewDate <[email protected] 

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 >[email protected] 
     and interviewDate <[email protected] 
    ) 
) t 
where rn = 1 
and interviewdate >[email protected] 
and interviewDate <[email protected] 
+0

是你用分區編輯足以讓我按最早的日期拉取數據,而日期不爲空? – FatBoySlim7

+1

'row_number()'是用'select'子句計算出來的,因此它只在用where子句過濾之後纔對行進行計數。 –

+0

對於PlanID - 在某些情況下,我有多個日期,但我有時也只有一個日期,其他值爲NULL。爲什麼當我只有一個日期並運行包含在問題中的SP時,當我通過PlanD順序通過AddedDate ASC執行分區時,我將該值拉到NULL值,但是,當我執行此操作時...分區由PlanID排序AddedDate Desc我得到日期。我希望能夠在這兩種情況下使用日期。由於某種原因,當我包括添加日期不爲空 - 我沒有得到我所有的數據(我猜一些PlanID的沒有添加日期) – FatBoySlim7