查询选择两个日期之间的内容

huangapple go评论61阅读模式
英文:

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&#39;03/12/2022&#39; and expecting it to be less than &#39;01/01/2023&#39;.

Instead, try:

DECLARE @today date = getdate();

SELECT
...
WHERE TRY_CONVERT(date, [Date], 103) &gt;= DATEADD(DAY, -30, @today)
  AND TRY_CONVERT(date, [Date], 103) &lt;= @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):

huangapple
  • 本文由 发表于 2023年3月9日 23:41:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686890.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定