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.

572<br />

CHAPTER 13 ■ PARTITIONING<br />

Hash Partition Using Powers of Two<br />

I mentioned earlier that the number of partitions should be a power of two. This is easily<br />

observed to be true. To demonstrate, we’ll set up a stored procedure to automate the creation<br />

of a hash partitioned table with N partitions (N will be a parameter). This procedure will construct<br />

a dynamic query to retrieve the counts of rows by partition <strong>and</strong> then display the counts<br />

<strong>and</strong> a simple histogram of the counts by partition. Lastly, it will open this query <strong>and</strong> let us see<br />

the results. This procedure starts with the hash table creation. We will use a table named T:<br />

ops$tkyte@ORA10G> create or replace<br />

2 procedure hash_proc<br />

3 ( p_nhash in number,<br />

4 p_cursor out sys_refcursor )<br />

5 authid current_user<br />

6 as<br />

7 l_text long;<br />

8 l_template long :=<br />

9 'select $POS$ oc, ''p$POS$'' pname, count(*) cnt ' ||<br />

10 'from t partition ( $PNAME$ ) union all ';<br />

11 begin<br />

12 begin<br />

13 execute immediate 'drop table t';<br />

14 exception when others<br />

15 then null;<br />

16 end;<br />

17<br />

18 execute immediate '<br />

19 CREATE TABLE t ( id )<br />

20 partition by hash(id)<br />

21 partitions ' || p_nhash || '<br />

22 as<br />

23 select rownum<br />

24 from all_objects';<br />

Next, we will dynamically construct a query to retrieve the count of rows by partition. It<br />

does this using the “template” query defined earlier. For each partition, we’ll gather the count<br />

using the partition-extended table name <strong>and</strong> union all of the counts together:<br />

25<br />

26 for x in ( select partition_name pname,<br />

27 PARTITION_POSITION pos<br />

28 from user_tab_partitions<br />

29 where table_name = 'T'<br />

30 order by partition_position )<br />

31 loop<br />

32 l_text := l_text ||<br />

33 replace(<br />

34 replace(l_template,

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

Saved successfully!

Ooh no, something went wrong!