call spQuery_Trabajador(NULL, NULL, NULL,NULL, null);

DROP PROCEDURE IF EXISTS spQuery_Trabajador;
CREATE PROCEDURE spQuery_Trabajador(
	varCodigo   int,
	varNombre   varchar(80),
	varDirecc   varchar(80),
  varField    varchar(60),
  varOrder    varchar(5)
)
BEGIN
  DECLARE varCadCod, varCadNom, varCadDir, varCadTip TEXT DEFAULT '';
  DECLARE varCadOrd TEXT DEFAULT '';
	if varCodigo <> '' and varCodigo is not null then
    set varCadCod = CONCAT(" and C.id_trabajador = ", varCodigo," ");
  end if;
	if varNombre <> '' and varNombre is not null then
    set varCadNom = CONCAT(" and concat(C.apellido_paterno, ' ', C.apellido_materno, ' ', C.nombre) like '%", varNombre,"%' ");
  end if;
  if varDirecc <> '' and varDirecc is not null then
    set varCadDir = CONCAT(" and C.direccion = ", varDirecc," ");
  end if;
   -- Para Ordenar
  IF varField is not null and varField <> '' THEN
    SET varField = CASE WHEN varField = 'FECHA_CREADO' THEN 'M._date_create'
                        WHEN varField = 'FECHA_MODIFI' THEN 'M._date_update'
                        ELSE varField
                   END;
    SET varCadOrd = CONCAT("ORDER BY ", varField, " ");
    IF varOrder is not null and varOrder <> '' THEN
      SET varCadOrd = CONCAT(varCadOrd, varOrder, " ");      
    END IF;
  END IF;
  
  SET @sql = CONCAT("select ",
                    "C.id_trabajador AS CTRA, concat(ifnull(C.apellido_paterno,''), ' ', ifnull(C.apellido_materno,''), ' ', ifnull(C.nombre,'')) AS TRABAJADOR, ",
                    "I.abrev as CDOC, C.nro_documento as DOCIDE, C.DIRECCION, ",
                    "C.sueldo_base_mensual as SUELDO_MES, C.sueldo_base_diario as SUELDO_DIA, C.porc_comision_venta as COMISION, ",
                    "C.TELEFONO1, C.TELEFONO2, C.CELULAR, C.RPM, C.RPC, C.NEXTEL, C.BREVETE, C.EMAIL, ",
                    "CASE WHEN estado='A' then 'ACTIVO' else 'INACTIVO' END AS ESTADO, ",
                    "date_format(C._date_create,'%d/%m/%Y %h:%i:%s %p') AS FECHA_CREADO, ",
                    "date_format(C._date_update,'%d/%m/%Y %h:%i:%s %p') AS FECHA_MODIFI, ",
                    "UPPER(UN.usuario) as USER_CREADO, ",
                    "UPPER(UU.usuario) as USER_MODIFI ",
                    "from _sv_trabajador C ",
                    "inner join _srh_tipo_doc_identidad I on C.id_tipo_doc_identidad = I.id_tipo_doc_identidad "
                    "left join _sys_usuario UN ON C._user_create = UN.id_usuario ",
                    "left join _sys_usuario UU ON C._user_update = UU.id_usuario ",
                    "where C._estado='A' ",
                    varCadCod, varCadNom, varCadDir,
                    varCadOrd);
                      
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;