Fixed #23909 -- Prevented crash when collecting SQL for RunSQL

Thanks James Rivett-Carnac for the report and Markus Holtermann
for the review.