如何获取两个日期范围内的数据列表

How to get list of data within two date range

我想知道在我的查询的两个日期范围内获取 uniqueidentifier 列的最佳方法是什么,如下所示

SELECT id, question, description
from Questions
where id between EffectiveFromDate and EffectiveToDate

Table问题的结构是:

[Id] Uniqueidentifier Code varchar(255) 
[Question] varchar(500) 
[EffectiveFromDate] datetime 
[EffectiveToDate] datetime 
[ModifiedDate] datetime

感谢您的帮助

正如你向我传达的问题,试试这个,如果你的要求不同,请告诉我。

您需要传递一个 DateTime 类型的列名进行比较。

SELECT id, question, description FROM Questions
WHERE Id=YourID AND dateColumn between EffectiveFromDate and EffectiveToDate

使用您在评论中发布的 table 结构。

Id Uniqueidentifier Code varchar(255) 
Question varchar(500) 
EffectiveFromDate datetime 
EffectiveToDate datetime 
ModifiedDate datetime

如果您想在 2 个日期之间提出有效问题:

Declare @DatetimeVar1 as Datetime = '2015-04-13 00:00:00'
Declare @DatetimeVar2 as Datetime = '2015-04-14 00:00:00'

Select * from Questions
where EffectiveFromDate between @DateTimeVar1 and @DateTimeVar2
or EffectiveToDate between @DateTimeVar1 and @DateTimeVar2

这会检查 EffectiveFromDate 或 EffectiveToDate 是否在您查询的 2 个日期之间。

首先你要明白BETWEEN

"Sql Between" Specifies a range to test.

语法:

select * from table_name
where
test_expression  BETWEEN begin_expression AND end_expression

test_expression Is the expression to test for in the range defined by begin_expressionand end_expression. test_expression must be the same data type as both begin_expression and end_expression.

begin_expression Is any valid expression. begin_expression must be the same data type as both test_expression and end_expression.

end_expression Is any valid expression. end_expression must be the same data type as both test_expression and begin_expression.

AND Acts as a placeholder that indicates test_expression should be within the range indicated by begin_expression and end_expression.

所以, 对于

SELECT id, question, description
from Questions
where id between EffectiveFromDate and EffectiveToDate

id,EffectiveFromDate,EffectiveToDate必须是相同的数据类型

而且我认为,它不在 . 希望您正在尝试在特定日期 select 所有 id

所以你需要尝试:

declare @startdate as date='01/02/2014'
declare @enddate as date='01/02/2015'

SELECT id, question, description
    from Questions
    where Cast(EffectiveFromDate as date) >=cast(@startdate as date)
and Cast(EffectiveToDate as date)<=cats(@enddate as date)