How To trim last two digit of the varchar in SQL SSMS?



  • I have a column [CALMONTH] which is a varchar in SQL Table. Data is like "202003" where 2020 is the year and 03 is the respective month. I need to trim the month'03' alone to use it in the analysis. how can I achieve the same?



  • Considering that the column always has six chars, you can use LEFT and RIGHT to separate the year part and the month part

    https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=f6e87741999ab46a6ffa7efaa6d837c6

    DECLARE @year_month VARCHAR(6) = '202003';
    DECLARE @year INT = LEFT(@year_month, 4), @month INT = RIGHT(@year_month, 2);
    SELECT @year_month AS input, @year AS year, @month AS month
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2