select * from _srh_colegio where id_departamento='01';

call spQuery_Colegio(NULL,NULL,'01','FECHA_CREADO',NULL);

DROP PROCEDURE IF EXISTS spQuery_Colegio;
CREATE PROCEDURE spQuery_Colegio(
  varCodigo varchar(5),
	varNombre varchar(80),
  varDepart varchar(2),
  varField  varchar(60),
  varOrder  varchar(5)
  )
BEGIN
  DECLARE varCadCod, varCadNom, varCadDep  text default '';
  DECLARE varCadOrd TEXT DEFAULT '';
  
  if varCodigo is not null or varCodigo <> '' then
    set varCadCod = CONCAT(" and A.id_colegio = '", varCodigo, "' ");
  end if;
  if ifnull(varNombre,'') <> '' then
    set varCadNom = CONCAT(" and A.nombre LIKE '%", varNombre, "%' ");
  end if;
  if ifnull(varDepart,'') <> '' then
    set varCadDep = CONCAT(" and A.id_departamento = '", varDepart, "' ");
  end if;
  -- Para Ordenar
  IF varField is not null and varField <> '' THEN
    SET varField = CASE WHEN varField = 'FECHA_CREADO' THEN 'A._date_create'
                        WHEN varField = 'FECHA_MODIFI' THEN 'A._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 A.id_colegio AS CCOL, A.nombre AS COLEGIO, ",
                    "A.id_dependencia as CDEI, X.nombre as DEPENDENCIA, ",
                    "A.id_departamento as CDEP, (select distinct departamento from _sv_ubigeo where id_pais='01' and substring(id_ubigeo,1,2)=A.id_departamento) as DEPARTAMENTO, ",
                    "date_format(A._date_create,'%d/%m/%Y %h:%i:%s %p') AS FECHA_CREADO, ",
                    "date_format(A._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 _srh_colegio A ",
                    "inner join _srh_colegio_dependencia X on A.id_dependencia = X.id_dependencia ",
                    "left join _sys_usuario UN ON A._user_create = UN.id_usuario ",
                    "left join _sys_usuario UU ON A._user_update = UU.id_usuario ",
                    "where A._estado='A' ",
                    varCadCod, varCadNom, varCadDep,
                    varCadOrd);		
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;