zoukankan      html  css  js  c++  java
  • 将一个字段的若干行转为一个字串(Oracle)

    1、使用for
    /*----------------------------------------------------------*/
    declare v_str varchar2(4000) := '';
            v_rowcount number := 0;
            v_top_n number := 3;
           
    begin
        select count(*)
        into v_rowcount
        from test;

        for x in 1..v_rowcount loop
            select v_str || t.username || ','
            into v_str
            from (select rownum as tempid, username from test) t
            where t.tempid = x;
           
            exit when x = v_top_n;
        end loop;

        v_str := substr(v_str, 1, (length(v_str) -1));
        dbms_output.put_line(v_str);
    end;
    /*----------------------------------------------------------*/

    2、使用loop
    /*----------------------------------------------------------*/
    declare
        v_str varchar2(2000):='';
        v_rownumber number :=0;
        v_top_n number := 3;
        v_i number:=1;

    begin
        select count(*)
        into v_rownumber
        from test;
       
        if (v_top_n > v_rownumber) then
            v_top_n := v_rownumber;
        end if;
       
        loop
            begin          
                select v_str || t.username || ','
                into v_str
                from (select rownum as id, username from test) t
                where t.id = v_i;           
                                     
                v_i := v_i + 1;           
                exit when (v_i > v_top_n);
            end;                
        end loop; 
       
        v_str := substr(v_str, 1, length(v_str) - 1);
        dbms_output.put_line(v_str);  
    end;
    /*----------------------------------------------------------*/


    /*----------------------------------------------------------*/
    The syntax for the substr function is:
    substr( string, start_position, [ length ] )

    说明:
    string is the source string.
    start_position is the position for extraction. The first position in the string is always 1.
    length is optional. It is the number of characters to extract. If this parameter is omitted, substr will return the entire string.
    /*----------------------------------------------------------*/

  • 相关阅读:
    bzoj 1800 & 洛谷 P2165 [AHOI2009]飞行棋 —— 模拟
    bzoj 1050 [ HAOI 2006 ] 旅行comf —— 并查集
    洛谷P2593 [ ZJOI 2006 ] 超级麻将 —— DP
    bzoj 3029 守卫者的挑战 —— 概率DP
    poj 2288 Islands and Bridges ——状压DP
    bzoj 1029 [ JSOI 2007 ] 建筑抢修 —— 贪心
    bzoj 3743 [ Coci 2015 ] Kamp —— 树形DP
    bzoj 1053 [ HAOI 2007 ] 反素数ant ——暴搜
    【构造共轭函数+矩阵快速幂】HDU 4565 So Easy! (2013 长沙赛区邀请赛)
    构造类斐波那契数列矩阵(矩阵
  • 原文地址:https://www.cnblogs.com/aspsmile/p/1277474.html
Copyright © 2011-2022 走看看