call spQuery_Sub_Area(NULL,NULL,'FECHA_CREADO',NULL);

DROP PROCEDURE IF EXISTS spQuery_Sub_Area;
CREATE PROCEDURE spQuery_Sub_Area(
  varCodigo int,
	varNombre varchar(80),  
  varField  varchar(60),
  varOrder  varchar(5)
  )
BEGIN
  DECLARE varCadCod, varCadNom  text default '';
  DECLARE varCadOrd TEXT DEFAULT '';
  
  if varCodigo is not null or varCodigo <> '' then
    set varCadCod = CONCAT(" and S.id_sub_area = ", varCodigo, " ");
  end if;
  if ifnull(varNombre,'') <> '' then
    set varCadNom = CONCAT(" and S.nombre LIKE '%", varNombre, "%' ");
  end if;
  -- Para Ordenar
  IF varField is not null and varField <> '' THEN
    SET varField = CASE WHEN varField = 'FECHA_CREADO' THEN 'S._date_create'
                        WHEN varField = 'FECHA_MODIFI' THEN 'S._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 S.id_sub_area AS CSUB, S.nombre AS SUBAREA, S.ABREV, ",
                    "S.id_area as CARE, A.nombre as AREA, ",
                    "date_format(S._date_create,'%d/%m/%Y %h:%i:%s %p') AS FECHA_CREADO, ",
                    "date_format(S._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_sub_area S ",
                    "inner join _srh_area A ON S.id_area = A.id_area ",
                    "left join _sys_usuario UN ON S._user_create = UN.id_usuario ",
                    "left join _sys_usuario UU ON S._user_update = UU.id_usuario ",
                    "where S._estado='A' ",
	                  varCadCod, varCadNom,
                    varCadOrd);		
  PREPARE s1 FROM @sql;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END;