Ocean Knight Ocean Knight - 2 months ago 10
SQL Question

How to get insert values from a table into an array using SQL?

with dmHospital do
begin
qryHospital.SQL.Clear;
qryHospital.SQL.Add('SELECT * FROM Patients ') ;
qryHospital.SQL.Add('WHERE DoctorID = :DoctorID');
qryHospital.Parameters.ParamByName('DoctorID').Value := StrToInt(sID);
qryHospital.Open;
iCount := qryHospital.RecordCount
end;


This code displays the values I want to put into the array. However I'm not sure how to cycle through each record and to get each value from the record into the correct array. For example: I want the names from 'PatientName' and the surnames from 'PatientSurname'.
iCount is the array size.

Answer

You must loop from TDataset using While.

Some sample code:

...
qryHospital.Open;
iCount := qryHospital.RecordCount;
// loop the recordset (while not arrive at end)
While (not qryHospital.eof) do begin
  Str1 := qryHospital.FieldByName('PatientName').AsString;
  Str2 := qryHospital.FieldByName('PatientSurname').AsString;

  // Add the values to array
  //...

  // Next Record
  qryHospital.Next;
end;

NOTE: For better performance, don't use FieldByName inside the loop (for big number of records). You can use Fields[index] or create a variable out of the loop and reference to fields.

Comments