05.11.2015 Views

Apress.Expert.Oracle.Database.Architecture.9i.and.10g.Programming.Techniques.and.Solutions.Sep.2005

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 11 ■ INDEXES 459<br />

7 l_last_digit number default 0;<br />

8<br />

9 type vcArray is table of varchar2(10) index by binary_integer;<br />

10 l_code_table vcArray;<br />

11<br />

12 begin<br />

13 stats.cnt := stats.cnt+1;<br />

14<br />

15 l_code_table(1) := 'BPFV';<br />

16 l_code_table(2) := 'CSKGJQXZ';<br />

17 l_code_table(3) := 'DT';<br />

18 l_code_table(4) := 'L';<br />

19 l_code_table(5) := 'MN';<br />

20 l_code_table(6) := 'R';<br />

21<br />

22<br />

23 for i in 1 .. length(p_string)<br />

24 loop<br />

25 exit when (length(l_return_string) = 6);<br />

26 l_char := upper(substr( p_string, i, 1 ) );<br />

27<br />

28 for j in 1 .. l_code_table.count<br />

29 loop<br />

30 if (instr(l_code_table(j), l_char ) > 0 AND j l_last_digit)<br />

31 then<br />

32 l_return_string := l_return_string || to_char(j,'fm9');<br />

33 l_last_digit := j;<br />

34 end if;<br />

35 end loop;<br />

36 end loop;<br />

37<br />

38 return rpad( l_return_string, 6, '0' );<br />

39 end;<br />

40 /<br />

Function created.<br />

Notice in this function, we are using a new keyword, DETERMINISTIC. This declares that<br />

the preceding function, when given the same inputs, will always return the exact same output.<br />

This is needed to create an index on a user-written function. We must tell <strong>Oracle</strong> that the function<br />

is DETERMINISTIC <strong>and</strong> will return a consistent result given the same inputs. We are telling<br />

<strong>Oracle</strong> that this function should be trusted to return the same value, call after call, given the<br />

same inputs. If this were not the case, we would receive different answers when accessing the<br />

data via the index versus a full table scan. This deterministic setting implies, for example, that<br />

we cannot create an index on the function DBMS_RANDOM.RANDOM, the r<strong>and</strong>om number generator.<br />

Its results are not deterministic; given the same inputs, we’ll get r<strong>and</strong>om output. The<br />

built-in SQL function UPPER used in the first example, on the other h<strong>and</strong>, is deterministic, so<br />

we can create an index on the UPPER value of a column.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!