18

我试图找出如何编写一个 SQL 语句来获取字符串不是 12 个字符长的字段。如果它们是 10 个字符,我只想获取字符串。

DB2 中有什么功能可以做到这一点?

我想它会是这样的,但我在上面找不到任何东西。
select * from table where not length(fieldName, 12)

4

3 回答 3

32

从类似的问题DB2 - find and compare the value of the value in a table field - 添加 RTRIM 因为 LENGTH 将返回列定义的长度。这应该是正确的:

select * from table where length(RTRIM(fieldName))=10

更新 27.5.2019:可能在较旧的 db2 版本上,LENGTH 函数返回列定义的长度。在 db2 10.5 上,我尝试了该函数,它返回数据长度,而不是列定义长度:

select fieldname
, length(fieldName) len_only
, length(RTRIM(fieldName)) len_rtrim
from (values (cast('1234567890  ' as varchar(30)) )) 
as tab(fieldName)

FIELDNAME                      LEN_ONLY    LEN_RTRIM
------------------------------ ----------- -----------
1234567890                              12          10

可以通过使用这个术语来测试这一点:

where length(fieldName)!=length(rtrim(fieldName))
于 2013-05-12T19:56:16.553 回答
29

这将获取长度为 10 个字符的字符串(在 fieldName 列中)的记录:

 select * from table where length(fieldName)=10
于 2012-07-05T15:19:02.830 回答
-1

通常我们在下面写语句 select * from table where length(ltrim(rtrim(field)))=10;

于 2019-04-03T11:20:54.220 回答