[英]Convert Decimal or Varchar into Date
I have 2 fields. 我有2个领域。
Birth= Datatype Decimal(12,4) & Date = Datatype Date 出生=数据类型十进制(12,4)&日期=数据类型日期
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) 其中Birth是Date数据类型而不是十进制(12,4)
To convert the number 19650101
to a date use 要将数字
19650101
转换为日期,请使用
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
). 这取决于您提供的确切格式(
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.