我正在尝试编写一个简单的过程,它将用逗号连接三个字段;但棘手的部分是,如果其中一个值丢失,那么我不想在没有第一个值(第二个字段,第三个字段)时看到前面的逗号 db版本:oracle 11gR2:
Declare
v_first_name varchar2(15);
v_last_name varchar2(15);
v_title varchar2(15);
ShowResult varchar2 (50);
Begin
v_first_name := nvl('john', null) ;
v_last_name := nvl('lennon',null);
v_title := nvl('singer',null);
ShowResult := v_first_name ||','|| v_last_name ||','|| v_title
I am expecting from ShowResult be like this : john,lennon, singer.
But if any of the value v_first_name or v_last_name or v_title
is null then, i like to ShowResult in this way :
1st scenario: lennon,singer -- if v_first_name is null
2nd scenario: john,singer -- if v_last_name is null
3rd scenario: singer -- if first name and last name r null
DBMS_OUTPUT.PUT_LINE ('Output is '|| ShowResult);
End;
答案 0 :(得分:1)
你可以尝试类似的东西:
ShowResult := LTRIM(COALESCE(v_first_name,'') || NVL2(v_last_name,',','') || COALESCE(v_last_name,'') || NVL2(v_title,',','') || COALESCE(v_title,''),',')
LTRIM()将删除前导逗号。
带有DECODE的版本:
ShowResult := LTRIM(COALESCE(v_first_name,'') || DECODE(v_last_name,null,'',',') || COALESCE(v_last_name,'') || DECODE(v_title,null,'',',') || COALESCE(v_title,''),',')