DB2 IF 和 LENGTH 用法

DB2 IF and LENGTH usage

我有这个 DB2 table

A      |  B      | C

aaaa   |123      |
bbbb   |1        |
cccc   |123456   |

所有列都是 varchars。我想让 C 列填满 B 的内容并与 A 的内容连接起来。 但是C的最大长度是8。所以如果连接的字符串超过8,那么我只想有5个字符+“...”。

基本上:

if(length(A) + length(B) > maximum(C) {
      //display only the first (maximum(C) - 3) characters, then add "..."
} else {
     // display B + A
}

我如何在 DB2 中执行此操作?

一个好的选择是将 C 列定义为生成的列,这样您就不必处理任何事情。

create table t3 (A varchar(10),
                 B varchar(10), 
                 C varchar(8) generated always as (case when length(concat(A, B)) > 8 then substr(concat(A,B),1,5) || '...' else concat(A, B) end)
                )

insert into t3 (A,B) values ('This', ' is a test');
insert into t3 (A,B) values ('ABCD', 'EFGH');
select * from t3

将return

A           B           C         
----------------------------------
This         is a test  This ...  
ABCD        EFGH        ABCDEFGH  

备选方案可以是触发器、过程、显式代码等。