[英]How to get the data/value size from CHAR column of Oracle Database?
I have a table in Oracle DB with column CHAR(11 ). 我在Oracle DB中有一个带有CHAR(11 )列的表。
I have inserted the value 'abcd ' to it. 我已将值“ abcd”插入其中。 (Note there is single space after abcd)
(请注意,abcd后面有一个空格)
When I do LENGTH(column) - it returns 11 instead of 5. 当我执行LENGTH(column)-返回11而不是5。
How do I get the data size instead of column size? 如何获取数据大小而不是列大小?
Reason I need it because I am reading the value from table1 having CHAR datatype and inserting the data to table2 having VARCHAR datatype . 我之所以需要它,是因为我正在从具有CHAR数据类型的 table1 中读取值,并将数据插入具有VARCHAR数据类型的 table2 中 。
So in this case, it adds 'abcd ' (abcd with trailing 7 spaces) to table2 instead of 'abcd ' (with single space). 因此,在这种情况下,它将“ abcd” (带有尾随7个空格的abcd)添加到table2中,而不是“ abcd” (带有单个空格)。
How do I avoid this? 如何避免这种情况? If I can get hold of data size from CHAR column then I can do that.
如果我可以从CHAR列中获取数据大小,则可以这样做。
Please let me know how it can be achieved? 请让我知道如何实现?
If you want a variable length column then use VARCHAR2
and not CHAR
. 如果要使用可变长度的列,请使用
VARCHAR2
而不是CHAR
。
A CHAR
column is a fixed length string that will be right-padded with space (ASCII 32) characters. CHAR
列是固定长度的字符串,将用空格(ASCII 32)字符右填充。 So, if you want the length of a CHAR(11)
then it will always be 11 characters regardless of whether you tried to insert a 1-character or an 11-character string as it will be right padded. 因此,如果您想要
CHAR(11)
的长度,则无论您是尝试插入1个字符还是11个字符的字符串,它都将始终为11个字符,因为它将被正确填充。
If you want to ignore the right padding then RTRIM
the string before measuring the length (however this will also remove any intentional trailing white spaces as well as the unintentional ones). 如果要忽略正确的填充,则在测量长度之前先对字符串进行
RTRIM
(但是这也会删除所有有意结尾的空格以及无意结尾的空格)。
SELECT LENGTH( RTRIM( column_name ) ) FROM table_name
For example: 例如:
Oracle Setup : Oracle安装程序 :
CREATE TABLE table_name ( column_name CHAR(11) );
INSERT INTO table_name ( column_name )
SELECT 'abcd' FROM DUAL UNION ALL
SELECT ' abc' FROM DUAL;
Query : 查询 :
SELECT LENGTH( column_name ),
LENGTH( TRIM( column_name ) ),
LENGTH( RTRIM( column_name ) )
FROM table_name
Output : 输出 :
\nLENGTH(COLUMN_NAME) |LENGTH(COLUMN_NAME)| LENGTH(TRIM(COLUMN_NAME)) |
LENGTH(TRIM(COLUMN_NAME))| LENGTH(RTRIM(COLUMN_NAME))
LENGTH(RTRIM(列))\n------------------: |
------------------:| ------------------------: |
------------------------:| -------------------------:
-------------------------:\n 11 |
11 | 4 |
4 | 4
4\n 11 |
11 | 3 |
3 | 4
4\n
As you can see, LENGTH
on its own includes the entire padded string. 如您所见,
LENGTH
本身包括整个填充字符串。 Using TRIM
gives the wrong answer as it also removes leading white-space as well as trailing white-space. 使用
TRIM
会给出错误的答案,因为它还会删除前导空白和尾随空白。 RTRIM
gives the correct length. RTRIM
给出正确的长度。
Please try with trim . 请尝试修剪。
select trim(column_name) from table; 从表中选择trim(column_name);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.