简体   繁体   中英

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.

Example: 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...

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; 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...

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM