Domanda

I need to pass a parameter to a SQL in Delphi using BDE to be using an "in", the example below:

select * from customers where id in (:p_in)

I need to pass: p_in a list of customers. But Query.ParamByName.('p_in').AsString: = '1, 2,3 ', and it did not work .. Will have to make an array? or passed by AsVariant?

È stato utile?

Soluzione 2

try this :

p_in  : String ;

for i := 0 to Customerlist.count do
   p_in := p_in +Customerlist[i] + ','; 

MyQuery.text := 'select * from customers where id in (' + p_in  + ' )' ;

Altri suggerimenti

You have to build your SQL dynamically. (See second half of my answer, though.)

var
  SQLStr: string;
  i: Integer;
begin
  SQLStr := 'SELECT * FROM Customers WHERE id IN (';
  for i := 0 to CustomerList.Count - 1 do
    SQLStr := SQLStr + QuotedStr(CustomerList[i]) + ',';
  // Replace final extra comma with closing ')'
  SQLStr[Length(SQLStr)] := ')';
  MyQuery.SQL.Text := SQLStr;
  ...
end;

Note that to prevent SQL injection, you should do this with parameterized SQL instead, although it takes more work. This would work as well, and be more safe:

var
  SQLStr: string;
  i: Integer;
begin
  SQLStr := 'SELECT * FROM Customers WHERE id IN (';

  // Add parameters to hold values like `:ID`
  for i := 0 to CustomerList.Count - 1 do
    SQLStr := SQLStr + Format(':ID%d,' [i]);

  // Remove final extra comma and replace with closing ')', and
  // then assign it to MyQry.SQL; the query will parse the params
  if CustomerList.Empty then
    SQLStr := SQLStr + ')'
  else
    SQLStr[Length(SQLStr)] := ')';
  MyQuery.SQL.Text := SQLStr;

  // Populate the parameters
  for i := 0 to CustomerList.Count - 1 do
    MyQuery.ParamByName(Format('ID%d', [i])).AsString := CustomerList[i];

  // Execute query
  MyQuery.Open;
end;

You can also directly replace them, if you have no other parameters in the SQL, but accessing them directly by index can cause problems if you change the query later and add a new parameter! Just replace the second for loop with this instead:

for i := 0 to CustomerList.Count - 1 do
  MyQuery.Params[i].AsString := CustomerList[i];

Since BDE is deprecated consider using modern components that allow substitution of parameters. Example:

SomeDataSet.SQL.Add('select foo from bar where baz in (:TESTIDS)');
SomeDataSet.DeclareVariable('TESTIDS', otSubst);  // <- this does the trick
// Place here some loop that fills the list of test-id separated by a ","
// And then:
SomeDataSet.SetVariable('TESTIDS', myIDList);  // Drop the list into the variable

Different component manufacturers might use different names for this.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top