0
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 应用于表字段时如何调用它们?

4

1 回答 1

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';
于 2016-08-16T18:56:27.527 回答