Install this theme

Posts tagged: sql

Oracle: Aggregating SQL statement results as single XML CLOB

Once again a short reminder how to aggregate SQL statement execution results as a single XML CLOB in Oracle.

Assume there is an Oracle table containing user data:

create table t_user(
	user_id		number(15) not null,	
	user_name	varchar2(100) not null,		
	role		varchar2(100) not null,			
	email		varchar2(100)	
)
/

Now aggregating all the user entries as single XML CLOB can be done using following statement:

select xmlelement("users",
                  xmlagg(xmlelement("user",
                                    xmlattributes(    t.user_id as "id",
                                                      t.user_name as "name",
                                                      t.role,
                                                      t.email
                                    )
            ))
        ).getclobval() xml
from t_user t

This will result in a CLOB that looks like this:

<users>
	<user id="1" name="foo" role="USER" email="[email protected]"></user>
	<user id="2" name="bar" role="ADMIN" email="[email protected]"></user>
	...
	<user id="999" name="xyz" role="USER" email="[email protected]"></user>
</users>  
MyBatis Generator Plugins

MyBatis is a data mapping framework providing capabilities to map SQL statements to Java Objects using Annotations or XML.

(Typical) Mapping rules can be written by hand or automatically generated by MyBatis Generator.

MyBatis Generator will generate:

  • SqlMap XML Files
  • Java Classes to match the primary key and fields of the table(s)
  • Java Client Classes that use the above objects (optional)

Furthermore it is possible to write custom plugins to enhance the generation process and to provide additional capabilities to generated sources.

Several months ago i’ve written some MyBatis Generator Plugins presented in this post. Check out the project’s source code on GitHub: https://github.com/bigpuritz/mybatis-generator-plugins

Keep reading

Getting n-th maximum row with SQL

This SQL statement will return n-th maximum row from the table:

select distinct a.myColumn
	from myTable a 
	where &n = (
		select count(distinct(b.myColumn))
		from myTable b
		where a.myColumn <= b.myColumn)

where &n is a max. row number to return.

For example this statement will return an employee with the second best salary:

select distinct a.name, a.salary
  from employee a
  where 2 = (select count(distinct(b.salary))
             from employee b
             where a.salary <= b.employee.salary)