Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine DB2 text string length

Tags:

sql

db2

I am trying to find out how to write an SQL statement that will grab fields where the string is not 12 characters long. I only want to grab the string if they are 10 characters.

What function can do this in DB2?

I figured it would be something like this, but I can't find anything on it.
select * from table where not length(fieldName, 12)

like image 660
Frantumn Avatar asked Jul 05 '12 15:07

Frantumn


People also ask

How do I find the length of a string in DB2?

The LENGTH() function With the IBM DB2 LENGTH function, when using a CHAR column, values are always blank padded, so the function returns the size of the CHAR column. When using a VARCHAR column, trailing blanks are significant, and the function returns the number of characters, including trailing blanks.

How do you find the length of a string in SQL?

The LEN() function returns the length of a string. Note: Trailing spaces at the end of the string is not included when calculating the length. However, leading spaces at the start of the string is included when calculating the length. Tip: Also look at the DATALENGTH() function.

How VARCHAR is defined in DB2?

Db2 VARCHAR type is used to store variable-length character strings. To define a variable-length character string column, you use the following syntax: column_name VARCHAR(n) In this syntax, n is a positive integer that represents the maximum length of n bytes that the column can store.

How do you check if a string contains a substring in DB2?

The Db2 INSTR() function finds a substring in a string and returns the position of the nth occurrence of the substring.


2 Answers

From similar question DB2 - find and compare the lentgh of the value in a table field - add RTRIM since LENGTH will return length of column definition. This should be correct:

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

UPDATE 27.5.2019: maybe on older db2 versions the LENGTH function returned the length of column definition. On db2 10.5 I have tried the function and it returns data length, not column definition length:

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

One can test this by using this term:

where length(fieldName)!=length(rtrim(fieldName))
like image 60
Robert Lujo Avatar answered Dec 07 '22 18:12

Robert Lujo


This will grab records with strings (in the fieldName column) that are 10 characters long:

 select * from table where length(fieldName)=10
like image 33
david a. Avatar answered Dec 07 '22 18:12

david a.