[英]Converting nvarchar (mm/yyyy) to DateTIme in Sql Server
I have a nvarchar column in Sql Server table which stores date values in mm/yyyy format. 我在Sql Server表中有一个nvarchar列,以mm / yyyy格式存储日期值。
Example: 03/2017 示例:03/2017
Now how to convert this string to datetime so that I can compare this date time with current date time (comparing Month and Year only) 现在如何将此字符串转换为日期时间,以便我可以将此日期时间与当前日期时间进行比较(仅比较月和年)
We can split and make this happen, like below: 我们可以拆分并实现这一点,如下所示:
declare @v varchar(7)
select @v = '03.2017'
select convert(datetime,right(@v,4) + left(@v,2) + '01')
尝试
Convert(datetime,'01/' + [field],103)
使用LEFT和RIGHT:
SELECT CONVERT(DATETIME, RIGHT('03/2017', 4) + '-' + LEFT('03/2017', 2) + '-01')
As mentioned, parsing the string is the right approach but I'll add this since it also shows getting the first day of the current month to compare against and that was mentioned in the original post. 如前所述,解析字符串是正确的方法,但是我将添加它,因为它还显示了获取当前月份的第一天与之进行比较,并且在原始帖子中已经提到了。
DECLARE @test varchar(10) = '03/2017'
DECLARE @firstOfMonth datetime
DECLARE @toCompare datetime
SELECT @firstOfMonth =
CAST(CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '/' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '/01' AS DATETIME)
SELECT @toCompare = CONVERT(datetime, right(@test, 4) + '-' + left(@test, 2) + '-01')
declare @strDate nvarchar(10) = '03/2017'
declare @newDate datetime = null
select @newDate= convert(date,replace(@strDate,'/','/1/'))
select month (@newdate)
select year (@newdate)
--now do your compare.---- -现在做你的比较----
Um, maybe I'm thick in the head, but it doesn't look like the OP wants to actually convert the NVARCHAR
value to a datetime... he just wants to compare the month and year from an NVARCHAR
value to the MONTH()
and YEAR()
of an actual DATETIME
value, and worded it a little poorly... 嗯,也许我头脑很笨拙,但是OP似乎并不想将
NVARCHAR
值实际转换为日期时间...他只是想将NVARCHAR
值中的月份和年份与MONTH()
和YEAR()
的实际DATETIME
值,并且措辞有点差...
The real answer, IMO, is that you can't convert MM/YYYY by itself to a DATETIME
value, which is why everyone is trying to add the first of the month; 真正的答案IMO是您不能将MM / YYYY本身转换为
DATETIME
值,这就是每个人都试图添加月初的原因。 but why not just do something like this... 但是为什么不做这样的事情...
SELECT *
FROM <sometable>
WHERE MONTH(<sometable>.<somecolumn>) = LEFT('03/2017',2)
AND YEAR(<sometable>.<somecolumn>) = RIGHT('03/2017',4)
;
And since the OP also asked about the "current date time, comparing month and year only", you could do... 并且由于OP还询问了“当前日期时间,仅比较月份和年份”,因此您可以...
SELECT *
FROM <sometable>
WHERE MONTH(GETDATE()) = LEFT(<somecolumn>,2)
AND YEAR(GETDATE()) = RIGHT(<somecolumn>,4)
;
I think that's what he meant to ask...? 我想这就是他要问的...? Maybe?
也许?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.