使用日期范围但结束日期的查询可以为空

时间:2016-06-03 16:06:57

标签: sql-server tsql

sql server 2014

我正在尝试使用日期范围查询数据。表中的数据是datetime数据类型。

所以我想用作参数@IncidentEndDate@IncidentEndDate

问题是(end_datetime IS NULL) AND (@IncidentDate >= CAST(start_datetime AS DATE) AND @IncidentDate <= DATEADD(d,0,DATEDIFF(d,0,start_datetime))) OR (@IncidentDate <= end_datetime) AND (@IncidentEndDate >= start_datetime) 可能为空。此外,数据中的每一行可能有也可能没有end_datetime(如果没有日期则为null)

在我的where子句中

WHERE (
      @IncidentDate <= isnull(end_datetime, dateadd(day,1,start_datetime))
   ) 
   AND (
   isnull(@IncidentEndDate,dateadd(day,1,@IncidentDate)) >= start_datetime
   )

但是我不确定这是否正常工作。我希望没有end_datetime的行出现在结果中,但它们似乎不是。

编辑:最后,我在阅读了所有人的回复后想出了以下内容......

end_datetime

在我看来,这是满足我的要求的更整洁的方式 - 它考虑了@IncdidentEndDate为空且Private Sub CommandButton2_Click() Dim Userentry As String Dim DataRange As Range Dim i As Long Dim location As Integer Dim ws, ws1 As Worksheet Set ws = Sheets("Sheet1") Set ws1 = Sheets("Sheet4") With TextBox2 Userentry = .Value End With Range("A36").Value = Userentry For i = 2 To ws.Range("A" & Rows.Count).End(xlUp).Row If LCase(Cells(i, 1).Value) = Userentry Then ws1.Range("F" & Rows.Count).End(xlUp).Offset(1, 0).Value = Cells(i, 2).Value Next i For i = 2 To ws.Range("A" & Rows.Count).End(xlUp).Row If LCase(Cells(i, 1).Value) = Userentry Then ws1.Range("G" & Rows.Count).End(xlUp).Offset(1, 0).Value = Cells(i, 3).Value Next i For i = 2 To ws.Range("A" & Rows.Count).End(xlUp).Row If LCase(Cells(i, 1).Value) = Userentry Then ws1.Range("H" & Rows.Count).End(xlUp).Offset(1, 0).Value = Cells(i, 4).Value Next i For i = 2 To ws.Range("A" & Rows.Count).End(xlUp).Row If LCase(Cells(i, 1).Value) = Userentry Then ws1.Range("I" & Rows.Count).End(xlUp).Offset(1, 0).Value = Cells(i, 5).Value Next i End Sub 为空的可能性

2 个答案:

答案 0 :(得分:2)

此外,您可以使用ISNULL()函数来帮助处理NULL值。 ISNULL()函数检查值,如果为NULL,则用提供的值替换它。因此,如果你想要NULL,你可以输入一个匹配的值,如果没有,那么肯定会超出你的范围的东西,如01/01/1900或MIN Date(根据DATETIME或DATETIME2而变化)。

要排除:

SELECT * FROM mySweetTable WHERE ISNULL(createdDate, GETDATE()) >= '01-JAN-2015'

包括:

//- foo.jade - var foo= "bar"

虽然,我不建议在WHERE子句中实际上留下GETDATE(),这是坏消息;用变量或特定值替换它。

答案 1 :(得分:0)

--This should get you what you want

start_datetime >= @IncidentDate and (@IncidentEndDate is null or end_datetime is null or end_datetime < dateadd(day,1,@IncidentEndDate))

当然,除非您要排除end_datetime is null以及For the First Case: 的情况,否则只是让我知道!