TSQL - 在数据库中搜索日期

时间:2016-06-02 07:14:07

标签: sql sql-server tsql

假设我有一个这样的表(它就像所有签名的历史表一样):

Id  Signature   From          To 
1   S01         2014-01-26    2016-01-26
2   S02         2016-01-26    2016-02-26
3   S03         2016-02-26    2016-04-26

现在我想知道2015-03-30之类的日期签名是什么?

3 个答案:

答案 0 :(得分:5)

使用between

DECLARE @date date = '2015-03-30'

SELECT [Signature]
FROM YourTable
WHERE @date between [From] and [To]

使用给定的样本数据执行示例:

DECLARE @DateTest TABLE (Id INT, [Signature] VARCHAR(5), [From] DATE, [To] DATE);

INSERT INTO @DateTest (Id, [Signature], [From], [To])
VALUES
(1, 'S01', '2014-01-26', '2016-01-26'),
(2, 'S02', '2016-01-26', '2016-02-26'),
(3, 'S03', '2016-02-26', '2016-04-26');

DECLARE @date DATE = '2015-03-30';

SELECT [Signature]
FROM @DateTest
WHERE @date BETWEEN [From] AND [To]

答案 1 :(得分:2)

您可以尝试使用:

select Signature   
from history
where '2015-03-30' between from and to

答案 2 :(得分:0)

一个日期

SELECT signature FROM Table where '2015-03-30' between from and to

OR

SELECT signature FROM Table where from<='2015-03-30' and to>='2015-03-30'