比较 T-SQL 中的日期
我有一个表,其中有一列数据类型为 varchar
的 date
。值为'2022-03-08 07:00',2022-03-08 07:30 ...
。
在我的存储过程中,我有一个类型为 DATE
的参数,其值为 '2022-3-8'
DECLARE @d DATE = '2022-3-8'
SELECT *, r.date AS date, @d AS d
FROM Readings AS r
WHERE CONVERT(VARCHAR, r.date, 23) = @d
我如何比较这两个?我收到此错误:
从字符串转换日期和/或时间时转换失败。
我想删除时间组件并比较 '2022-03-08'
与 '2022-3-8'
。请注意月份和日期数字中的前导零。
I have a table with a column date
of datatype varchar
. The values are '2022-03-08 07:00',2022-03-08 07:30 ...
.
In my stored procedure I have a parameter of type DATE
and with a value '2022-3-8'
DECLARE @d DATE = '2022-3-8'
SELECT *, r.date AS date, @d AS d
FROM Readings AS r
WHERE CONVERT(VARCHAR, r.date, 23) = @d
How can I compare these two? I get this error:
Conversion failed when converting date and/or time from character string.
I would like to remove time component and compare '2022-03-08'
vs '2022-3-8'
. Notice leading zero in month and day numbers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
TRY_CAST
或TRY_CONVERT
会将字符串转换为日期,如果不可能,则返回 null。例子:
TRY_CAST
orTRY_CONVERT
will convert your string into date and return null if that is not possible.Example:
使用 right(replicate('0',2)+value,2) 可以将1 位数字更改为两位数字( 1=>01)。
使用 PARSENAME 表示分割,使用 concat 表示连接字符串
或在查询中
use right(replicate('0',2)+value,2) that enables you to change a 1 one_digit number to two_digit number(1=>01).
use PARSENAME for split and concat for connect strings
or in your query