英文:
Query to Select between 2 dates
问题
我有一个开始日期和结束日期。我想要获取这两个日期之间的日期列表。可以有人帮我指出我的查询中的错误。
序号 | 值 | 日期 |
---|---|---|
1 | abc | 2023年2月14日 |
2 | def | 2023年2月14日 |
3 | efg | 2023年2月14日 |
4 | fgh | 2023年3月1日 |
由于日期列是nvarchar,我将其转换后在查询中使用
Select * from 表 where
(Convert(varchar(30),日期,103) >= Convert(varchar(30),getdate()-30,103)
and Convert(varchar(30),日期,103) <= Convert(varchar(30),getdate(),103))
上述查询应该列出我的表中的所有记录。然而,结果是0条记录。我尝试使用between
也得到相同的结果。
请建议。
英文:
I have a start and end dates. I want to get the list of dates in between these two dates. Can anyone help me pointing the mistake in my query.
SlNo | Value | Date |
---|---|---|
1 | abc | 14/02/2023 |
2 | def | 14/02/2023 |
3 | efg | 14/02/2023 |
4 | fgh | 01/03/2023 |
Since the Date Column is a nvarchar, I'm converting it and then using it in my Query
Select * from Table where
(Convert(varchar(30),Date,103) >= Convert(varchar(30),getdate()-30,103)
and Convert(varchar(30),Date,103) <= Convert(varchar(30),getdate(),103))
the above query should be listing all the records in my table. However it results in 0 records. I tried using the between which results the same
Please advise
答案1
得分: 0
修复列。永远不要将日期存储为字符串。
与此同时,您的问题在于,您将一个字符串转换为一个略有不同的字符串。这仍意味着您正在比较,比如,字符串 N'03/12/2022'
与期望它小于 01/01/2023
。
改为尝试:
DECLARE @today date = getdate();
SELECT
...
WHERE TRY_CONVERT(date, [Date], 103) >= DATEADD(DAY, -30, @today)
AND TRY_CONVERT(date, [Date], 103) <= @today;
然后修复列。以防我之前没有提到,永远不要将日期存储为字符串。
有关日期/时间最佳实践的更多信息,请参考这里(包括为什么不应该使用 getdate()-30
):
英文:
Fix the column. Never store a date as a string.
In the meantime, your problem is you're converting a string to a slightly different string. This still means you're comparing, say, the string N'03/12/2022'
and expecting it to be less than '01/01/2023'
.
Instead, try:
DECLARE @today date = getdate();
SELECT
...
WHERE TRY_CONVERT(date, [Date], 103) >= DATEADD(DAY, -30, @today)
AND TRY_CONVERT(date, [Date], 103) <= @today;
Then fix the column. In case I didn't mention it before, never store a date as a string.
Lots more on best practices with date/time here (including why we shouldn't say getdate()-30
):
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论