Hi
On below code i am getting error - The conversion of a varchar data type to a datetine data resulted in out-of-range value.
SQL
(SELECT PaymentDate = STUFF((
SELECT ',' + A0.docdate from Orct A0 inner join Rct2 A1 on A1.Docnum = A0.docentry and A1.baseabs = T0.docentry
FOR XML PATH('')
), 1, 1, ''))Thanks

Vishal YelveRank #178 · 13.6K reputationPosted Oct 26, 2023, 2:16 AM EDT
Hi Ramco,
try this
(SELECT PaymentDate = STUFF(( SELECT ',' + convert(datetime, A0.docdate) from Orct A0 inner join Rct2 A1 on A1.Docnum = A0.docentry and A1.baseabs = T0.docentry FOR XML PATH('') ), 1, 1, ''))OR
(SELECT PaymentDate = STUFF(( SELECT ',' + CONVERT(VARCHAR, A0.docdate, 101) from Orct A0 inner join Rct2 A1 on A1.Docnum = A0.docentry and A1.baseabs = T0.docentry FOR XML PATH('') ), 1, 1, ''))Tahir AnsariRank #366 · 6.8K reputationPosted Oct 26, 2023, 2:17 AM EDT
Hi Ramco,
SELECT PaymentDate = STUFF(( SELECT ',' + CONVERT(varchar, A0.docdate, 120) FROM Orct A0 INNER JOIN Rct2 A1 ON A1.Docnum = A0.docentry AND A1.baseabs = T0.docentry FOR XML PATH('') ), 1, 1, '')Jayraj ChhayaRank #304 · 8.2K reputationPosted Dec 26, 2023, 5:23 AM EST
Hi Ramco Ramco,
ProblemThe problem lies in the conversion of the
Causedocdatecolumn from theOrcttable to a datetime data type.The cause of the error is that the
docdatecolumn contains a value that cannot be converted to a valid datetime format. This could be due to various reasons, such as incorrect data entry or a mismatch between the expected datetime format and the actual value.Solution
To fix the error, we need to ensure that the values in the
docdatecolumn are in a valid datetime format. Here are a few steps you can take to resolve the issue:docdatecolumn of theOrcttable. Look for any values that are not in the expected datetime format.docdatecolumn. You can either update the values directly or use a conversion function to transform them into the correct format.Here's an example of how you can use the
TRY_CONVERTfunction to handle the conversion and exclude any invalid datetime values:(SELECT PaymentDate = STUFF(( SELECT ',' + TRY_CONVERT(datetime, A0.docdate) from Orct A0 inner join Rct2 A1 on A1.Docnum = A0.docentry and A1.baseabs = T0.docentry FOR XML PATH('') ), 1, 1, ''))By using the
TRY_CONVERTfunction, any values in thedocdatecolumn that cannot be converted to a valid datetime format will be returned asNULL. This will prevent the conversion error and allow the query to execute successfully.Subarta RayRank #336 · 7.4K reputationPosted Dec 26, 2023, 1:20 AM EST
SELECT PaymentDate = STUFF((
SELECT ',' + CONVERT(varchar, A0.docdate, 120)
FROM Orct A0
INNER JOIN Rct2 A1 ON A1.Docnum = A0.docentry AND A1.baseabs = T0.docentry
WHERE ISDATE(A0.docdate) = 1 -- Ensure it's a valid date
FOR XML PATH('')
), 1, 1, '')