如何将sql查询的结果保存到变量中,然后在脚本中使用它?

问题描述 投票:0回答:1

我有以下脚本:

    cl scr;
    variable l number;
    begin
      select max(length(name)) into :l from goodcustomer;
    end;
    /
    --print :l;
    alter table goodcustomer modify name varchar2(:l);

我正在尝试将名称的长度属性修改为表中当前存在的名称的最大长度(为17)。上面的代码在sql developer中给我以下错误:

    Error report -
    SQL Error: ORA-00910: specified length too long for its datatype
    00910. 00000 -  "specified length too long for its datatype"
    *Cause:    for datatypes CHAR and RAW, the length specified was > 2000;
               otherwise, the length specified was > 4000.
    *Action:   use a shorter length or switch to a datatype permitting a
               longer length such as a VARCHAR2, LONG CHAR, or LONG RAW 

我在这里做错了什么? l是不是可用于给出varchar2大小的数字?任何其他达到相同目的的方法也将受到赞赏?

sql oracle oracle11g oracle10g oracle-sqldeveloper
1个回答
1
投票

也许您可以使用动态SQL。示例(Oracle 18c):

表格

SQL> create table goodcustomer ( name varchar2( 4000 ) ) ;

Table created.

SQL> 
SQL> describe goodcustomer 
Name   Null?   Type             
NAME           VARCHAR2(4000)

插入一些名称

SQL> begin
  2    insert into goodcustomer values( 'shortestname' ) ;
  3    insert into goodcustomer values( 'l o n g e s tname' ) ;
  4  end ;
  5  /

PL/SQL procedure successfully completed.

SQL> select max( length( name ) ) from goodcustomer ;
  MAX(LENGTH(NAME)) 
                 17 

ALTER TABLE ... MODIFY

SQL> declare
  2    l number := 0 ;
  3    sqlstr varchar2( 4000 ) := '' ;
  4  begin
  5    select max( length( name ) ) into l from goodcustomer ;
  6    sqlstr := 'alter table goodcustomer modify name varchar2( ' 
  7           || to_char( l ) 
  8           || ')' ;
  9    execute immediate sqlstr ;
 10  end ;
 11  /

PL/SQL procedure successfully completed.

-- The NAME column now: VARCHAR2( 17 )
SQL> describe goodcustomer
Name   Null?   Type           
NAME           VARCHAR2(17) 

其他阅读,可能会为您澄清一些事情(替代变量还是绑定变量),请参见here

© www.soinside.com 2019 - 2024. All rights reserved.