简体   繁体   English

DB2 SQL将CHAR转换为SMALLINT

[英]DB2 SQL converting CHAR to SMALLINT

I have a CHAR column that I need to convert to a SMALLINT column. 我有一个CHAR列,我需要将其转换为SMALLINT列。 The CHAR column is defined as CHAR(4) and contains data like this '360 ' with a space at the end. CHAR列定义为CHAR(4)并包含类似'360 '数据,并在末尾有一个空格。

I tried to use the CAST function like this: 我试图像这样使用CAST函数:

CAST(DCA_REVN_CD AS SMALLINT) AS REVN_CD

This is the error I get: 这是我得到的错误:

-420 THE VALUE OF A STRING ARGUMENT WAS NOT ACCEPTABLE TO THE SMALLINT FUNCTION. -420字符串参数的值不适合SMALLINT函数。

Can anyone help? 有人可以帮忙吗? I realize it's probably because there is a space in the data. 我意识到这可能是因为数据中有空间。

As asked above...would TRIM() work? 如上所述,TRIM()是否可以工作?

Not sure if this would work, as I haven't coded in DB2 for a few years, but this did work with MSSQL: 不知道这是否行得通,因为我几年来都没有在DB2中进行编码,但这确实适用于MSSQL:

CAST(RTRIM(LTRIM(DCA_REVN_CD)) AS SMALLINT) AS REVN_CD

or the DB2 version (I think): 或DB2版本(我认为):

CAST(TRIM(DCA_REVN_CD) AS SMALLINT) AS REVN_CD

If you only have trailing spaces, then the SMALLINT function or your CAST will work: 如果只有尾随空格,则SMALLINT函数或CAST将起作用:

$ db2 "create table test (id smallint, value char(10))" ;
$ db2 "insert into test values (1, '1  ')" ;
$ db2 "insert into test values (2, '2 ')" ;
$ db2 "insert into test values (3, '3')" ;
$ db2 "select smallint(VALUE) from test";
1
-----------
          1
          2
          3

So, your CAST should work, which implies that you've got strings other than spaces in that column: 因此,您的CAST应该可以正常工作,这意味着您在该列中除了空格以外还具有其他字符串:

$db2 "insert into test values (4, '4 A')" ;
$db2 select SMALLINT(VALUE) from test";
SQL0420N  Invalid character found in a character string argument of the
function "SMALLINT".  SQLSTATE=22018

Sugguestion: If you're on db2 11 or later, you could use REGEXP_SUBSTR to extract just the digits from this column. 建议:如果您使用的是db2 11或更高版本,则可以使用REGEXP_SUBSTR从该列中仅提取数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM