Ver Mensaje Individual
  #1  
Antiguo 29-11-2008
[coso] coso is offline
Miembro Premium
 
Registrado: may 2008
Ubicación: Girona
Posts: 1.678
Reputación: 0
coso Va por buen camino
Query filtrada por texto

A esta función se le pasa un texto y te devuelve una query en la que en alguno de sus campos de texto esten todas las palabras en el texto pasado (sin importar el orden). Dicho de otra manera, si en la base de datos tengo en el campo, por ejemplo, DESCRIPCION los valores TEJANOS AZUL y en MARCA tengo JEAN, pasando a esta funcion "AZUL JEAN TEJANOS" te encontrara ese registro.

Código Delphi [-]
function SQLFilter(text,tablename,fixedfilter : string;cnx : TADOConnection) : TADOQuery;
var
     q : TADOQuery;
     t,s,
     n : string;
     i : integer;
     sl : TStringList;
begin
     q := TADOQuery.Create(Application);
     q.Connection := cnx;

     q.Active := false;
     q.SQL.Text := 'select * from ' + TableName;
     q.Active := true;

     if trim(text) <> '' then
     begin
          s := '(';
          for i := 0 to q.Fields.count - 1 do
          begin
               n := q.Fields[i].FieldName;

               if not (q.FieldByName(n).DataType in [ftString,ftMemo,ftFmtMemo,ftFixedChar,ftWideString]) then continue;

               if s <> '(' then s := s + '+'' ''+';
               s := s + 'IIF('+UpperCase(n)+','+UpperCase(n)+',''0'')';
          end;

          sl := TStringList.Create;
          sl.CommaText := text;
          t := ' where ';
          for i := 0 to sl.count - 1 do
          begin
               if t <> ' where ' then t := t + ' and ';
               t := t + s + ' like ' + QuotedStr(Comod_SQL+sl[i]+Comod_SQL) + ')';
          end;
          sl.free;
     end
     else t := '';

     if FixedFilter <> ''
     then
     if t <> '' then t := t + ' and ' + FixedFilter
     else t := ' where ' + FixedFilter;

     q.Active := false;
     q.SQL.Text := 'select * from ' + TableName + t;
     q.Active := true;

     result := q;
end;

y un ejemplo de uso

Código Delphi [-]
var 
      q : TADOQuery;
begin
      q := SQLFiltro('JERSEY AZUL','',dm.Conexion);
      q.Edit;
      q.FieldByName('COLOR').Asstring := 'ROJO';
      q.Post;
      q.Free;      
end;


Si lo que se quiere es buscar alguna de las palabras, solo hay que sustituïr el ' and ' por ' or '. La función crea el query, por lo que debe liberarse despues de ser usada (si no se quiere esa formulación, se puede usar el encabezado

Código Delphi [-]
procedure SQLFilter(text,tablename,fixedfilter : string;cnx : TADOConnection;var q : TADOQuery);
)
Responder Con Cita