简体   繁体   中英

Convert Decimal or Varchar into Date

I have 2 fields.

Birth= Datatype Decimal(12,4) & Date = Datatype Date

Birth         Date 
19650101   2015-07-09  

how do i get a result that looks like this

i want the result to be like this

Birth             Date          
1965-01-01       2015-07-09       

where the Birth is a Date datatype and not a decimal (12,4)

To convert the number 19650101 to a date use

CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112)

To get the number of years (to one decimal) you could do:

ROUND(
    DATEDIFF(day,
         CONVERT(DATETIME, CAST(Birth AS VARCHAR(8)), 112),
         [Date])/365.25
     ,1)

Which won't be exact but should be close enough to tenths of a year.

You can use this:

-- Create demo data
CREATE TABLE #dates(birth int, date date)

INSERT INTO #dates(birth,date)
VALUES(19650101,N'2015-07-09')

-- Your work
SELECT CONVERT(date,CONVERT(nvarchar(max),birth),112) as birth, date, 
        DATEDIFF(year,
            CONVERT(date,CONVERT(nvarchar(max),birth),112),
            date
        ) as years
FROM #dates

-- Cleanup
DROP TABLE #dates

This depends on the exact format you provides ( 19650101 ).

I think you don't need to round. Just convert your decimal value and put "-" like below : )

select left(birth,4) +'-' + 
substring(convert(nvarchar,birth),5,2)+'-'+ 
substring(convert(nvarchar,birth),7,2)

这是进行此转换的一种方法。

cast(cast(FLOOR(birth) as CHAR(8)) as DATE)

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