转换到最新最佳方式(Optimal way to convert to date)

2019-10-21 12:56发布

I have legacy system where all date fields are maintained in YMD format. Example:

20101123
this is date: 11/23/2010

I'm looking for most optimal way to convert from number to date field.

Here is what I came up with:

declare @ymd int

set @ymd = 20101122

select @ymd, convert(datetime, cast(@ymd as varchar(100)), 112)

This is pretty good solution but I'm wandering if someone has better way doing it

Answer 1:

尝试这个:

CONVERT(DATETIME, CONVERT(NVARCHAR, YYYYMMDD))

例如:

SELECT CONVERT(DATETIME, CONVERT(NVARCHAR, 20100401))

结果是:

2010-04-01 00:00:00.000


Answer 2:

你有什么是一个相当不错的soltuion。

你为什么要寻找一个更好的办法?



Answer 3:

我用的正是这样,它已经为我工作的罚款



Answer 4:

因为它是存储为一个整数,那么你可以通过100,1000除以潜在提取年,月,日。

DECLARE @Date INT
SET @Date = 20100401

DECLARE @Year INT
DECLARE @Month INT
DECLARE @Day INT

SET @Year = @Date / 10000
SET @Month = (@Date - (@Year * 10000)) / 100
SET @Day = @Date - (@Year * 10000) - (@Month * 100)

SELECT @Date, DATEADD(MONTH,((@Year-1900)*12)+@Month-1,@Day-1)

但是,我不知道,如果这是比你已经拥有的字符串比较快。 我认为您的解决方案是更干净,更易于阅读,并会与坚持。



文章来源: Optimal way to convert to date