create table test as select 'abcd' col from dual;
字段col数据类型默认为char(4)现在如果insert into test select 'abcdef' from dual; 会提示长度大如果insert into test select 'ab' from dual;可以插入
但select * from test where col='ab';
有时有数据,有时没有,可能是不同数据库对char类型设置的问题
特别是alter table test modify(col varchar2(20));后
select * from test where col='ab';就永远不行
而必须使用select * from test where col='ab  '; varchar2和char对字符串末尾有空格 怎么有这个差别不想每次都用alter modify和update
能不能在建表时同时指定数据类型

解决方案 »

  1.   

    [create tabel as select]这样建表大部分用在复制建表的时候。
    就是说有一个元表,然后再生成根据这个元表结构上一样(字段结构是一样的)表的时候用这种建表方式。
    按楼主的要求,你先建表,然后再插入数据不就行了么?
      

  2.   

    [create tabel as select]这样建表大我觉得是做子表,复制一部分数据跟表的结构,至于怎么改,研究中,我个人觉得这种情况不大好改。
      

  3.   

     create table tbb as (select '111aa' zf from dual union all select '111aaaaa' zf from dual)像这样建表就插入记录的语句不行 这是根据你插入的记录的最大长度定位最大的长度 而且是char类型的  所以有些数据的实际长度没有达到最大的长度就会补空格
    必须alter table tbb modify col varchar2(n)
    update tbb set col=replace(col,' ','')
      

  4.   

    varchar2是不定长的,定义时只会规定一个最大长度N,该字段上可以存储任意的比N短的字符
    char是定长的,定义时规定其长度N,插入数据时会用空格补位,就是说该字段上存储的数据长度都是N至于“不想每次都用alter modify和update”,如果你以“create table test as select ”方式建表,我觉得可能不能避免。
      

  5.   

    char类型在检索时会把右边的空格trim掉
      

  6.   

    SQL> create table tab_char
      2  (id number(10),
      3   name char(4));
     
    Table created
     
    SQL> insert into tab_char values(1,'1');
     
    1 row inserted
     
    SQL> 
    SQL> create table tab_char_bak
      2  as
      3  select id,rtrim(cast(name as varchar2(100))) name  from tab_char;
     
    Table created
     
    SQL> select * from tab_char_bak where name='1';
     
             ID NAME
    ----------- --------------------------------------------------------------------------------
              1 1
     
    SQL> 
    这样做的代价就是写create table  as select 语句的时候比较麻烦.
      

  7.   

    SQL> desc tab_char_bak 
    Name Type          Nullable Default Comments 
    ---- ------------- -------- ------- -------- 
    ID   NUMBER(10)    Y                         
    NAME VARCHAR2(100) Y                         
     
    SQL> 
      

  8.   

    --也可以用借助cast 加销空格函数trim来达到目的  
    SQL> create table tbb as select cast(trim('111aa') as varchar2(10)) zf from dual
      2  /
     
    Table created
     
    SQL> desc tbb
    Name Type         Nullable Default Comments 
    ---- ------------ -------- ------- -------- 
    ZF   VARCHAR2(10) Y                         
     
    SQL> select zf,length(zf) from tbb
      2  /
     
    ZF         LENGTH(ZF)
    ---------- ----------
    111aa               5
     
      

  9.   

    多写一句废话,尽量使用rtrim,不建议使用trim,因为char是在后面补空的,rtrim能多保真一些数据.
      

  10.   

    谢谢大家
    rtrim(cast(name as varchar2(100))) 就是要这个功能