I think you need to look at escaping any single quotes in your SQL statement. You can do this by adding another single quote next to any single quote in your SQL.
For example
TO_DATE(SUBSTRING(trgt_frm_ym, 1, 4) || ''-'' || SUBSTRING(trgt_frm_ym, 5, 2) || ''-01'', ''YYYY-MM-DD'')
The documentation on String functions explains a bit more about escaping quotes in strings.
https://docs.mendix.com/refguide/string-function-calls/
Good luck!