0
declare
  str varchar2(4000);
  i int;
begin
  for i in 1 ..31 loop

    str:= str || 'col' || i || ' varchar2(2)';
    if i < 31 then
       str := str || ',';
    end if;
  end loop;
  execute immediate 'create table t1  ('|| str ||')';
end;
/

I'm newbie in pl/sql this procedure creates t1 table with 31 columns. 31 is day of month (say May). I can't create the procedure which have condition like this : if col(i) i in ('Sat','Sun') ... insert into t1 value ('r') for example, this procedure must insert 'r' into col5,col6,col12,col13 .. columns because 5th,6th,12th,13th of may in Sun or Sat

 BEGIN   
   FOR i IN 1..31 LOOP
     IF( to_char(sysdate-1+i,'DAY')  IN ('SAT', 'SUN') )
     THEN
       INSERT INTO t1 (col(i))
         VALUES ('r');
     END IF;   
   END LOOP;  
 END;  
 /

I tried with this procedure but there are several errors where must I correct my mistakes thanks in advance

4

2 回答 2

4

I agree with Bob Jarvis that you ought to have a better data model. But just for grins let's assume you have to work with what you've got.

This procedure takes a month and year as parameters, and generates a range of days from them. I have given the MON_T table two columns, MON and YR as a primary key, because I can't help myself.

create or replace procedure gen_month_rec 
     ( p_mon in mon_t.mon%type
       ,  p_yr in mon_t.yr%type )
is
    lrec mon_t%rowtype;
    empty_rec mon_t%rowtype;
    first_dt date;
    last_d pls_integer;
begin
    lrec := empty_rec;
    lrec.mon := p_mon;
    lrec.yr := p_yr;

    first_dt := to_date('01-'||p_mon||'-'||p_yr, 'dd-mon-yyyy');
    last_d := to_number(to_char(last_day(first_dt),'dd'));

    for i in 1 .. last_d 
    loop
        if to_char(first_dt-+ (i-1),'DAY') in ('SAT', 'SUN') 
        then
            execute immediate 'begin lrec.col'
                                   ||trim(to_char(i))
                                   ||' := ''r''; end;';
        end if;
    end loop;

    insert into mon_t values lrec;
end;
于 2012-05-08T07:01:15.377 回答
2

I suggest that you read up on the rules of data normalization. It appears that this table suffers from a major problem in that it has what are known as "repeating groups" - in this case, 31 fields for information about each day. You probably need a table with the full date you're interested in, and then the fields which describe that date. Perhaps something like the following:

CREATE TABLE CALENDAR_DAY
  (CAL_DATE         DATE PRIMARY KEY,
   COL              NUMBER,
   <definitions of other fields needed for each day>);

Given the above your code becomes

 DECLARE
   dtMonth_of_interest  DATE := TRUNC(SYSDATE, 'MONTH');
 BEGIN   
   FOR i IN 0..30 LOOP
     IF( to_char(dtMonth_of_interest+i,'DAY')  IN ('SAT', 'SUN') )
     THEN
       INSERT INTO CALENDAR_DAY (CAL_DATE, COL)
         VALUES (dtMonth_of_interest + i, 'r');
     END IF;   
   END LOOP;  
 END;  

Hopefully this gives you some ideas.

Share and enjoy.

于 2012-05-08T01:58:54.127 回答