year from yyddmm

Shambhu Rai 1,411 Reputation points
2023-03-31T16:19:33.8066667+00:00

Hi Expert,

how to extract year from yyddmm

20220202

and convert format to date like 02-0202022

Azure SQL Database
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,361 questions
SQL Server Reporting Services
SQL Server Reporting Services
A SQL Server technology that supports the creation, management, and delivery of both traditional, paper-oriented reports and interactive, web-based reports.
2,878 questions
SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,525 questions
SQL Server Analysis Services
SQL Server Analysis Services
A Microsoft online analytical data engine used in decision support and business analytics, providing the analytical data for business reports and client applications such as Power BI, Excel, Reporting Services reports, and other data visualization tools.
1,263 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Viorel 114.7K Reputation points
    2023-03-31T16:45:59.73+00:00

    Check an example:

    declare @example int = 20220203 -- 2 March 2022
    
    select 
    	@example / 10000 as [year], 
    	datefromparts(@example / 10000, @example % 100, @example % 10000 / 100) as [date]
    
    0 comments No comments

  2. PercyTang-MSFT 12,426 Reputation points Microsoft Vendor
    2023-04-03T02:59:29.1966667+00:00

    Hi @Shambhu Rai

    What is the type of '20220202' in the example, int, char or something else?

    I looked for it in this official document and couldn't find the date format of yyddmm.

    https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15

    Extract the year: If it is an int type, you only need to divide by 10000 as Viorel demonstrated. If it is a char type, you can use the LEFT() function to truncate the year.

    convert format to date like 02-0202022

    Which date format is this, can you explain further?

    Best regards,

    Percy Tang


    If the answer is the right solution, please click "Accept Answer". If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  3. Olaf Helper 43,246 Reputation points
    2023-04-03T07:53:32.4333333+00:00

    Convert it to varchar and then to date:

    select convert(date, convert(varchar(8), 20220202))
    
    
    0 comments No comments