一条SQL语句没有办法实现,可以通过存储过程,用游标实现。

解决方案 »

  1.   

    简单写了一个过程,各位看看还有没有更好的办法。CREATE OR REPLACE FUNCTION p_test
    return varchar2
    is
         str varchar2(20);
         i integer;
         iid integer;
         frand numeric(16,2);
         cursor cursor1 is
          select id,dbms_random.value() rand from t_test where type = 1 order by rand;
         cursor cursor2 is
          select id,dbms_random.value() rand from t_test where type = 2 order by rand;
    begin
         str := '';
         i := 0;
         open cursor1;
         loop
              fetch cursor1 into iid,frand;
              exit when cursor1%notfound;
              i := i + 1;
              if i <= 2 then
                 str := str||iid||':';
              end if;
         end loop;   
         close cursor1;
         open cursor2;
         i := 0;
         loop
              fetch cursor2 into iid,frand;
              exit when cursor2%notfound;
              i := i + 1;
              if i <= 2 then
                 str := str||iid||':';
              end if;
              if i = 3 then
                 str := str||iid;
              end if;
         end loop;   
         close cursor2;
         return str;
    end ;
      

  2.   

    create or replace function getIDs return varchar2 is
      Result varchar2(100) Default '';
    begin
      for x in (
         select id
         from (
            select id from (select id,dbms_random.value() rand from t_test where type = 1 order by rand) where rownum<=2 
            union 
            select id from (select id,dbms_random.value() rand from t_test where type = 2 order by rand) where rownum<=3
         ) )
      loop
        Result := Result||':'||x.id;
      end loop;
      if length(Result)>1 then
        Result := substr(Result,2);
      end if;
      return(Result);
    end getIDs;select getIDs AS myIDs from dual;