文本环绕在oracle中

时间:2011-02-23 07:29:04

标签: sql oracle

我们如何根据标准长度包装文本(列值),在ORACLE SQL中只允许40个字符到多行。

3 个答案:

答案 0 :(得分:4)

select regexp_replace(column_name, '(.{40})', '\1' || chr(10) || chr(13))
from some_table;

答案 1 :(得分:2)

在SQL Plus中,您可以指定列宽

column column_name format a40 
select column_name from table_name

以上格式化输出为40列宽,它会将任何内容包装到下一行。

输出显示通常由客户端控制

答案 2 :(得分:0)

我从Martin Burbridge获得的一些代码并进行了修改:

CREATE OR REPLACE FUNCTION line_wrap(p_str_to_wrap             VARCHAR2
                                    ,p_max_linesize            PLS_INTEGER
                                    ,p_indent_spaces_each_line PLS_INTEGER DEFAULT 0
                                    ,p_separator               VARCHAR2 DEFAULT ' ') RETURN VARCHAR2 IS
  -- This function will insert chr(10)'s (newlines) at the separator 
  --  nearest the specified linesize.
  -- The separator will default to a space if none provided.
  -- The p_indent_spaces_each_line parameter allows each line of wrapped text to be
  --  indented x spaces if desired. The indent_spaces will default to 0 if none provided. 
  v_max_linesize            PLS_INTEGER := nvl(p_max_linesize
                                              ,80);
  v_indent_spaces_each_line PLS_INTEGER := nvl(p_indent_spaces_each_line
                                              ,0);
  v_separator               VARCHAR2(20) := nvl(p_separator
                                               ,' ');
  v_str_to_wrap             VARCHAR2(4000) := p_str_to_wrap || v_separator;
  v_line                    VARCHAR2(4000);
  v_position                PLS_INTEGER;
  v_wrapped_text            VARCHAR2(4000);
  v_sql_errmsg              VARCHAR2(4000);

BEGIN
  WHILE v_str_to_wrap IS NOT NULL
  LOOP
    v_line     := substr(v_str_to_wrap
                        ,1
                        ,v_max_linesize);
    v_position := instr(v_line
                       ,v_separator
                       ,-1);
    IF v_position = 0
    THEN
      v_position := v_max_linesize;
    END IF;

    v_line := substr(v_line
                    ,1
                    ,v_position);

    IF v_indent_spaces_each_line > 0
    THEN
      v_wrapped_text := v_wrapped_text || chr(10) || lpad(' '
                                                         ,v_indent_spaces_each_line
                                                         ,' ') || v_line;
    ELSE
      v_wrapped_text := v_wrapped_text || chr(10) || v_line;
    END IF;

    v_str_to_wrap := substr(v_str_to_wrap
                           ,v_position + 1);
  END LOOP;

  RETURN v_wrapped_text;

EXCEPTION
  WHEN OTHERS THEN
    v_sql_errmsg := 'Error in word_wrap: ' || SQLERRM;
    raise_application_error(-20001
                           ,v_sql_errmsg);
END;

-- How to use this function in a select statement:
select line_wrap(my_string,
                 40,
                 2,
                 ' ')
  from my_table.