使用标题案例查询结果填充ComboBox

时间:2016-08-16 18:51:23

标签: delphi combobox access database-table tadoquery

with TdmBCElections.Create(Self) do
begin
  with dmBCElections, qryParties do
  begin
    SQL.Clear;
    if rgpParty.ItemIndex = 0 then
      SQL.Text := 'SELECT StrConv(P_Surname, 3), StrConv(P_Names, 3) ' +
      'FROM Parties WHERE P_Type = "HEAD"'
    else
      SQL.Text := 'SELECT StrConv(P_Surname, 3), StrConv(P_Names, 3) ' +
      'FROM Parties WHERE P_Type = "TEACHER"';
    Open;
    while not Eof do
    begin
      cmbDetails.Items.Add(qryParties['StrConv(P_Surname, 3)'] + ', ' +
        qryParties['StrConv(P_Names, 3)']);
      Next;
    end;
  end;
end;

上面的代码给出了以下错误消息:

qryPartiesError

如何在应用StrConv时调用表字段?

1 个答案:

答案 0 :(得分:6)

您可以为字段指定别名:

with TdmBCElections.Create(Self) do
begin
  with dmBCElections, qryParties do
  begin
    if rgpParty.ItemIndex = 0 then
      SQL.Text := 'SELECT StrConv(P_Surname, 3) as ConvertedSurname, StrConv(P_Names, 3) as ConvertedNames ' +
      'FROM Parties WHERE P_Type = "HEAD"'
    else
      SQL.Text := 'SELECT StrConv(P_Surname, 3) as ConvertedSurname, StrConv(P_Names, 3) as ConvertedNames ' +
      'FROM Parties WHERE P_Type = "TEACHER"';
    Open;
    while not Eof do
    begin
      cmbDetails.Items.Add(qryParties['ConvertedSurname'] + ', ' +
        qryParties['ConvertedNames']);
      Next;
    end;
  end;
end;

否则,您可以使用字段索引而不是名称:

with TdmBCElections.Create(Self) do
begin
  with dmBCElections, qryParties do
  begin
    if rgpParty.ItemIndex = 0 then
      SQL.Text := 'SELECT StrConv(P_Surname, 3), StrConv(P_Names, 3) ' +
      'FROM Parties WHERE P_Type = "HEAD"'
    else
      SQL.Text := 'SELECT StrConv(P_Surname, 3), StrConv(P_Names, 3) ' +
      'FROM Parties WHERE P_Type = "TEACHER"';
    Open;
    while not Eof do
    begin
      cmbDetails.Items.Add(qryParties.Fields[0].AsString + ', ' + qryParties.Fields[1].AsString);
      Next;
    end;
  end;
end;

无论哪种方式,我建议您考虑使用参数化查询:

SQL.Text := 'SELECT ... FROM Parties WHERE P_Type = :PType';
if rgpParty.ItemIndex = 0 then
  Parameters.ParamByName('PType').Value := 'HEAD'
else
  Parameters.ParamByName('PType').Value := 'TEACHER';