日期:2014-05-17  浏览次数:21766 次

create tabel as select 在建表时如何指定数据类型
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
能不能在建表时同时指定数据类型









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

------解决方案--------------------
[create tabel as select]这样建表大我觉得是做子表,复制一部分数据跟表的结构,至于怎么改,研究中,我个人觉得这种情况不大好改。
------解决方案--------------------
探讨
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 w……

------解决方案--------------------
varchar2是不定长的,定义时只会规定一个最大长度N,该字段上可以存储任意的比N短的字符
char是定长的,定义时规定其长度N,插入数据时会用空格补位,就是说该字段上存储的数据长度都是N

至于“不想每次都用alter modify和update”,如果你以“create table test as select ”方式建表,我觉得可能不能避免。
------解决方案--------------------
char类型在检索时会把右边的空格trim掉
------解决方案--------------------
SQL code
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>

------解决方案--------------------
SQL code
SQL> desc tab_char_bak 
Name Type          Nullable Default Comments 
---- ------------- -------- ------- -------- 
ID   NUMBER(10)    Y                         
NAME VARCHAR2(100) Y                         
 
SQL>

------解决方案--------------------
探讨
引用:
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;可以插入
但……

------解决方案--------------------
powerful
------解决方案--------------------
cast
这东西好。。。。
------解决方案--------------------
多写一句废话,尽量使用rtrim,不建议使用trim,因为char是在后面补空的,rtrim能多保真一些数据.