Search code examples
sqlsql-serverdatestring-concatenationnvarchar

Concat and make a string into a date


I have a table where the month and year are separate, and I want to put them together and make the backend format to date. I tried cast/converting but I get an error of "Conversion failed when converting date and/or time from character string"

This is the data

Accountingperiod | Accounting year
1                    2023
2                    2024
3                    2023
10                   2024

desired out put or any date output as long as its date

01/01/2023
02/01/2024
03/01/2023
10/01/2024

and when I output I try to cast the result but I get an error because of the string . Here is my code

select cast(concat(tb.AccountingPeriod,tb.AccountingYear) as date) as month_year_date  
from  ttbl_a  tb 

Solution

  • Thanks @siggemannen, I used the below and it gave me what I want.

    select DATEFROMPARTS (AccountingYear,AccountingPeriod,1) as yy_mm_date from ttbl_a
    
    output
    
    yy_mm_date
    2023 -01-01  
    2024 -02-01 
    2023 -03-01 
    2024 -10-01