2016-11-08 5 views
1

私は、Oracleデータベースを使用していくつかの先行ゼロをトリムする必要がありますが、少なくとも4文字にフィールドの長さを埋めるために十分な先行ゼロを残す必要があります。SQLはいくつかの先行をトリム0

myField  cooked 
0000000009  0009 
000
00ABCE1234 ABCE1234 

私は私の目標を達成するために、これを使用しますが、より良い方法

があるかどう思っていた:これは「myFieldで」が入力されると「調理」私は出力として望むものであるいくつかのサンプルデータであり、
case 
    when length(trim(leading 0 from myfield)) >= 4 then trim(leading 0 from myfield) 
    else lpad(trim(leading 0 from myfield), 4 , 0) 
end as cooked 

答えて

4

ありがとうございます!例えば、regexp_substr()を使用して:

with 
    test_data (myfield) as (
     select '0000000009' from dual union all 
     select '000' from dual union all 
     select '00ABCE1234' from dual 
    ) 
-- end of test data; solution (SQL query) begins below this line 
select myfield, regexp_substr(myfield, '^0+(.{4,}$)', 1, 1, null, 1) as cooked 
from test_data 
; 

MYFIELD COOKED 
---------- ---------- 
0000000009 0009  
000
00ABCE1234 ABCE1234 

これはmyfieldは少なくとも4文字の長さであるとみなします。そうでない場合には、ゼロで埋めなければならない場合は、myfield'0000' || myfieldに置き換えることができます。

関連する問題