简体   繁体   中英

SQL Server: Convert varchar numbers to date

Is it possible to convert a varchar numbers to date? I am fetching data from a table and I want it converted into date. Can you help me figure this out? There is an error on the last part:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

declare @year varchar(6)
declare @month varchar(2)
declare @test varchar (8)


set @year = right(left('F20160316-1000',5),4)
select @year

set @month = right(left('F20160316-1000',7),2)
select @month

set @test = @month +''+ @year
select @test

SELECT CONVERT (DATETIME, CONVERT(varchar(12),@test))

Anyway, the the result that I want to achieve is MAR2016 .

The way you are storing and converting is not good as Jarlh pointed out.You could use datetimefrom parts to get output ,in your case day is missing ,i added it..

  declare @year varchar(6)
  declare @month varchar(2)
  declare @day varchar (8)

  set @year = right(left('F20160316-1000',5),4)
  set @month = right(left('F20160316-1000',7),2)    
  Set @day=right(left('F20160316-1000',5),2)

  select datetimefromparts(@year,@month,@day)

further if your string pattern is same ,you can do this as well..

declare @string varchar(15)
set @string='F20160316-1000'
select convert(datetime,substring(@string,2,charindex('-',@string,1)-2)

Output: 2016-03-16 00:00:00.000

Try like this,

DECLARE @year VARCHAR(6)
DECLARE @month VARCHAR(2)
DECLARE @test VARCHAR(8)

SET @year = right(left('F20160316-1000', 5), 4)
SET @month = right(left('F20160316-1000', 7), 2)
SET @test = @year + @month + '01'

SELECT UPPER(CONVERT(VARCHAR(3), DATENAME(MM, @test), 100)) + @year AS MonthYear

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