SSIS - Get Year based on Month

Cynthia McMahon 46 Reputation points
2022-12-08T14:17:37.26+00:00

Good morning. I have a bit of a quandary. I have an SSIS package that dynamically imports files from the previous month. The files are coded with the name of the month in text and the year. I have the month working correctly. The year is not working correctly. It currently gets the year based on the system date. The problem is if it is January, it should return the previous year. I have two variables that hold the month and year. It would be great if somebody could shine some light on this dilemma.

SUBSTRING("December  January   Febuary   March     April     May       June      July      August    September October   November  ",((DATEPART("MONTH",GETDATE())-1)*10)+1,9)  
  
REPLACE(SUBSTRING((DT_STR,50,1252)GETDATE(),1,4),"-","_")  
SQL Server Integration Services
0 comments No comments
{count} votes

Answer accepted by question author
  1. ZoeHui-MSFT 41,536 Reputation points
    2022-12-09T02:46:21.36+00:00

    Hi @Cynthia McMahon

    If the date format is like '2022-Dec-09', you may use expression to get the previous year if the month is Jan.

    SUBSTRING(yourdatecolumn,6,3)== "Jan" ?(YEAR( (DT_DBTIMESTAMP)(yourdatecolumn))-1):YEAR( (DT_DBTIMESTAMP)(yourdatecolumn))  
    

    You may modify the expression with your date setting.

    Regards,

    Zoe Hui


    If the answer is helpful, please click "Accept Answer" and upvote it.


1 additional answer

Sort by: Most helpful
  1. Yitzhak Khabinsky 27,091 Reputation points
    2022-12-08T15:41:14.193+00:00

    Hi @Cynthia McMahon ,

    (1) You would need to add '01' to your input to compose a real date in the following format: yyyy-MM-dd:

    <your_input_date> =  (DT_DATE)('yyyy' + "-" + "MM" + "01")  
    

    (2) After that use DATEADD() function to go back one month:

    DATEADD("Month", -1,<your_input_date>)  
    

    (3) Use DATEPART() function to get YEAR and MONTH for your needs.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.