Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Trucos (https://www.clubdelphi.com/foros/forumdisplay.php?f=52)
-   -   Query filtrada por texto (https://www.clubdelphi.com/foros/showthread.php?t=80889)

coso 29-11-2008 11:40:37

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);
)

coso 29-11-2008 11:43:58

Comod_SQL es, dependiendo del servidor usado (Access o SQL General) '*' o '%'


La franja horaria es GMT +2. Ahora son las 02:11:53.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi