2016-03-21 48 views
0

我有这样的DB2表DB2 IF和长度使用

A  | B  | C 

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

所有列VARCHAR处理。我想让列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?

+0

什么背景?它是一个SELECT或INSERT语句,一个函数或存储过程,还是......?你看过'CASE'吗? –

回答

1

一个不错的选择是将列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 

将返回

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

替代品可能是触发器,过程,明确代码等

+0

这听起来像一个很棒的想法。谢谢! –