Question

A SQL Server application we use (accpac) represents dates as an 8 digit decimal in ISO format (example: today's date is 20100802)

I need to add one month to this. I've found a way to do it, but there must be a better way. The steps of my solution are:

declare @accpacDate as decimal
set @accpacDate = 20100101

declare @date1 as date
declare @date2 as date

set @date1=cast(CAST(@accpacDate as varchar(8)) as datetime) /*get the starting value as a date */
set @date2=DATEADD(month,1,@date1)

select CONVERT(varchar(8),@date2,112) as aVarchar 
select convert(decimal,CONVERT(varchar(8),@date2,112)) as aDecimal
Was it helpful?

Solution

It seems about right what you are doing.

String and Date manipulation is pretty core in SQL, no fancy wrappers for auto-converting and manipulating date formats (accpac, memories, shiver).

You could write that into a user function, to add days to a accpac date, and return the result:

create function accpacadd 
(   @accpacdate decimal,
    @days int)
RETURNS decimal
AS BEGIN

declare @date1 as datetime

set @date1=cast(CAST(@accpacDate as varchar(8)) as datetime) /*get the starting value as a date */
set @date1=DATEADD(day, @days, @date1)
return convert(decimal, CONVERT(varchar(8), @date1, 112)) 

END

So then you can just call it with min code:

select dbo.accpacadd(20100102, 5)
select dbo.accpacadd(20100102, -5)

Gives 20100107 and 20091228 respectively

OTHER TIPS

SELECT CONVERT(VARCHAR(8),DATEADD(MONTH,1,CONVERT(VARCHAR(8),20100802,112)),112)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top