Dec 8, 2011

Try this Query

select * from tmp_table m1where
from
(2-1)=(select count(distinct(m2.age)) tmp_table m2 where m2.age>m1.age) 
 

else
1. Query will return all rows from tmp_table if point 2 is true will return 0 rows.2. (select count(distinct(m2.age)) from tmp_table m2 where m2.age>m1.age)=1There is a cross product between tmp_table m2 and tmp_table m1, so from tmp_table m2 where m2.age>m1.age will return many rows.thus if count of distinct of age from the table tmp_table m2 is 1 then TRUE.Thus if age of all rows in table tmp_table is same... it will return all rows else will retun 0 rowsThus if age of all rows in table tmp_table is same... Query will return all rows else will retun 0 rows

Nov 12, 2011

SQL Loader with XML DATA

1. conn hr/hr
2. create table load_test of xmltype;
3. exit fom user
4. create a control file test.ctl


LOAD DATA
INFILE *
TRUNCATE INTO TABLE load_test
XMLType(xmldata)
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
(
xmldata
)
BEGINDATA
KING<  ./name><  ./  EMP>,
SCOTT<. /name><  ./EMP>,
SMITH< . /name><  ./EMP>

5. c:\> sqlldr hr/hr control= c:\test.ctl

6. sqlplus
   hr/hr
   select * from load_test;



Example to store xmltype data from sql*loader
1. conn hr/hr
2. create table load_test of xmltype;
3. create a data file c:\person.dat - contains XML data

4. create a control file c:\load.ctl
LOAD DATA
INFILE *
INTO TABLE test_load
APPEND XMLType(XMLDATA)
(
 lobfn FILLER CHAR TERMINATED BY ',',
 XMLDATA LOBFILE(lobfn) TERMINATED BY ''
 )
BEGINDATA
c:\person.dat

5. c:\> sqlldr hr/hr
control=c:\load.ctl
6.sqlplus
hr/hr
select * from load_test;


Export and Import Data from XML Schema Database

UserName :  sys as dba   passward:   oracle

SQL> show parameter db_name;
It will shows database name

SQL> exit;

Q> How to setup my SID?

A>  set oracle_sid <2nd DBname>



export from user oe to user scott
Export: Release 10.1.0.4.2 - Production on Fri Nov 11 17:41:39 2011
Copyright (c) 1982, 2005, Oracle.  All rights reserved.

Username: oe/oe
Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Produc
tion
With the Partitioning, OLAP and Data Mining options
Enter array fetch buffer size: 4096 >
Export file: EXPDAT.DMP > c:\ware.dmp
(2)U(sers), or (3)T(ables): (2)U > t
Export table data (yes/no): yes > Y
Compress extents (yes/no): yes > Y
Export done in WE8MSWIN1252 character set and AL16UTF16 NCHAR character set
TA
About to export specified tables via Conventional Path ...
Table(T) or Partition(T:P) to be exported: (RETURN to quit) > WAREHOUSES
. . exporting table                     WAREHOUSES          9 rows exported
Table(T) or Partition(T:P) to be exported: (RETURN to quit) >
Export terminated successfully without warnings.
C:\


***************************************************
TO IMPORT DATA FROM C:\WARE.DMP FILE TO USER SCOTT
C:\> IMP SCOTT/TIGER FILE=C:\WARE.DMP FULL=Y










XML Topics

Day 1:
 1. XML Introduction
2.  Introduction with Tags.
3.  DTD - Data Type Defination
4.  Namespaces
5.  Examples.
6.  XMLDB in Oracle 10G
7. Features and Usage of XMLDB
8. XMLType


XML -> Platform Independent , it can Store data and transfer the data

HTML --> Display the Data of XML

Root, Element and Attributes, Child and Subchild.


Day 2:

1. XQuery
2. XML SQL Functions
3. DML Operation Functions

XMLQuery() and XMLTable()

Day 3:

1. Schema Introduction

2. Schema Registration

3. Table Creation with Schema

4. Constraint in XMLType Table

5. To Check Validation of Schema

6. SQL Loader

7. Export and Import

8. XPath

Nov 11, 2011

DBMS_XMLSTORE SQL functions

How to Modify XML Data?

DBMS_XMLSTORE SQL functions is used for to replace, insert, and delete XML data without replacing the entire surrounding XML document. This means that you can perform piecewise manipulation operations on an XML document by using SQL functions.

You use the following SQL functions:
updateXML() to replace XML nodes of any kind insertChildXML(), insertXMLbefore(), and appendChildXML() to insert XML data deleteXML() to delete XML data

The SQL functions insertChildXML(), insertXMLbefore(), and appendChildXML() can perform updates that are more localized than with updateXML(), thereby greatly improving performance and making source code clearer and more concise.

Do not use the updateXML() function to insert or delete XML data by replacing a parent node in its entirety. Although this works, it is less efficient than using one of the other available functions, which perform more localized updates.

XQuery expressions in Oracle 10g

What are and How to use XQuery Expressions
XQuery expressions are case-sensitive. The expressions include the following:
  • primary expression – literal, variable, or function application. A variable name starts with a dollar-sign ($) – for example, $foo. Literals include numerals, strings, and character or entity references.
  • XPath expression – Any XPath expression. The developing XPath 2.0 standard will be a subset of XQuery. XPath 1.0 is currently a subset, although XQuery uses a richer type system.
  • FLWOR expression – The most important XQuery expression, composed of the following, in order, from which FLWOR takes its name: forletwhere , order byreturn.
  • XQuery sequence – The comma (,) constructor creates sequences. Sequence-manipulating functions such as union and intersect are also available. All XQuery sequences are effectively flat: a nested sequence is treated as its flattened equivalent. Thus, for instance, (1, 2, (3, 4, (5), 6), 7) is treated as (1, 2, 3, 4, 5, 6, 7). A singleton sequence, such as (42), acts the same in most XQuery contexts as does its single item, 42. Remember that the result of any XQuery expression is a sequence.
  • Direct (literal) constructions – XML element and attribute syntax automatically constructs elements and attributes: what you see is what you get. For example, the XQuery expression 33 constructs the XML element33.
  • Computed (dynamic) constructions – You can construct XML data at runtime using computed values. For example, the following XQuery expression constructs this XML data: tata titi why? .
·                {attribute toto {2+3}, element bar {"tata", "titi"}, text {" why? "}
·               
In this example, element foo is a direct construction; the other constructions are computed. In practice, the arguments to computed constructors are not literals (such as toto and "tata"), but expressions to be evaluated (such as 2+3). Both the name and the value arguments of an element or attribute constructor can be computed. Braces ({}) are used to mark off an XQuery expression to be evaluated.
  • Conditional expression – As usual, but remember that each part of the expression is itself an arbitrary expression. For instance, in this conditional expression, each of these subexpressions can be any XQuery expression:somethingsomethingElseexpression1, and expression2.
·                if (something < somethingElse) then expression1 else expression2
·               
  • Arithmetic, relational expression – As usual, but remember that each relational expression returns a (Boolean) value. Examples:
·                2 + 3
·                42 < $a + 5
·                (1, 4) = (1, 2)
·                5 > 3 eq true()
·               
  • Quantifier expression – Universal (every) and existential (some) quantifier functions provide shortcuts to using a FLWOR expression in some cases. Examples:
·                every $foo in doc("bar.xml")//Whatever satisfies $foo/@bar > 42
·                some $toto in (42, 5), $titi in ("xyz12", "abc", 5) satisfies $toto = $titi
·               
  • Regular expression – XQuery regexes are based on XML Schema 1.0 and Perl.
  • Type expression – An XQuery expression that represents an XQuery type. Examples: item()node()attribute()element()document-node()namespace()text()xs:integerxs:string
Type expressions can have occurrence indicators? (optional: zero or one), * (zero or more), + (one or more). Examples: document-node(element())*item()+attribute()?.
XQuery also provides operators for working with types. These include cast ascastable astreat asinstance oftypeswitch, and validate. For example, "42" cast as xs:integer is an expression whose value is the integer 2. (It is not, strictly speaking, a type expression, because its value does not represent a type.)

XMLForest SQL Function-- How to use it...

How to use XMLForest?

SQL function XMLForest produces a forest of XML elements from its arguments, which are expressions to be evaluated, with optional aliases.

Example 1:
 Generating Elements with Attribute and Child Elements
This example generates an Emp element for each employee, with a name attribute and elements with the employee hire date and department as the content.
SELECT XMLElement("Emp",
                  XMLAttributes(e.first_name ||' '|| e.last_name AS "name"),
                  XMLForest(e.hire_date, e.department AS "department"))
AS "RESULT"
FROM employees e WHERE e.department_id = 20;


Example 2:
Generating an Element from a User-Defined Datatype Instance
You can also use SQL function XMLForest to generate hierarchical XML from user-defined datatype instances.
SELECT XMLForest(
  dept_t(department_id,
         department_name,
         CAST (MULTISET (SELECT employee_id, last_name
                           FROM hr.employees e
                           WHERE e.department_id = d.department_id)
               AS emplist_t))
         AS "Department")
  AS deptxml
  FROM hr.departments d
  WHERE department_id=10;


 

XMLSEQUENCE SQL Function

How to use and what is XMLSEQUENCE SQL Function?

SQL function XMLSequence returns an XMLSequenceType value (a varray of XMLType instances). Because it returns a collection, this function can be used in the FROM clause of SQL queries.

Example 1:
SELECT value(T).getstringval() Attribute_Value
  FROM table(XMLSequence(extract(XMLType('V1V2V3'),
                                 '/A/B'))) T;

Example 2:
CREATE TABLE emp_xml_tab OF XMLType;

Table created.
INSERT INTO emp_xml_tab VALUES( XMLType('
                                           112Joe50000217
                                             Jane
                                             60000412Jack40000'));
1 row created.
COMMIT;


To create a new XML document containing only employees who earn $50,000 or more, you can use the following query:

SELECT sys_XMLAgg(value(em), XMLFormat('EMPLOYEES'))
  FROM emp_xml_tab doc, table(XMLSequence(extract(value(doc),
                                          '/EMPLOYEES/EMP'))) em
  WHERE extractValue(value(em), '/EMP/SALARY') >= 50000;


These are the steps involved in this query:
Function extract returns a fragment of EMP elements.
Function XMLSequence gathers a collection of these top-level elements into XMLType instances and returns that.
Function table makes a table value from the collection. The table value is then used in the query FROM clause.


Example 3:

XMLSEQUENCE: Generate a Document for Each Row of a Cursor
In this example, SQL function XMLSequence is used to create an XML document for each row of a cursor expression, and it returns an XMLSequenceType value (a varray of XMLType instances).
SELECT value(em).getClobVal() AS "XMLTYPE"
  FROM table(XMLSequence(Cursor(SELECT *
                                  FROM hr.employees
                                  WHERE employee_id = 104))) em;


Example 4:
XMLSEQUENCE: Unnesting Collections in XML Documents into SQL Rows

CREATE TABLE dept_xml_tab OF XMLType;

Table created.

INSERT INTO dept_xml_tab
  VALUES(
    XMLType('
               Sports
              
                 John33333
                

                 Jack333444
                

              

            
'));

1 row created.

INSERT INTO dept_xml_tab
  VALUES (
    XMLType('
               Sports
              
                 Marlin20000
                

              

            
'));

1 row created.

COMMIT;


SELECT extractValue(OBJECT_VALUE, '/Department/@deptno') AS deptno,
       extractValue(value(em), '/Employee/@empno') AS empno,
       extractValue(value(em), '/Employee/Ename') AS ename
  FROM dept_xml_tab,
       table(XMLSequence(extract(OBJECT_VALUE,
                                 '/Department/EmployeeList/Employee'))) em;

XMLAGG SQL Function-- How to use it...

How to use XMLAGG SQL Functions ..

SQL function XMLAgg is an aggregate function that produces a forest of XML elements from a collection of XML elements.

Example 1:
 Generating Department Elements with a List of Employee Elements
This example produces a Department element containing Employee elements with employee job ID and last name as the contents of the elements. It also orders the employee XML elements in the department by their last name. (The actual result is not pretty-printed.)
SELECT XMLElement("Department", XMLAgg(XMLElement("Employee",
                                                  e.job_id||' '||e.last_name)
                                       ORDER BY e.last_name))
  AS "Dept_list"    
  FROM hr.employees e
  WHERE e.department_id = 30 OR e.department_id = 40;

Example 2:
The result is a single row, because XMLAgg aggregates the rows. You can use the GROUP BY clause to group the returned set of rows into multiple groups. (The actual result of the following query is not pretty-printed.)
SELECT XMLElement("Department", XMLAttributes(department_id AS "deptno"),
                  XMLAgg(XMLElement("Employee", e.job_id||' '||e.last_name)))
   AS "Dept_list"
   FROM hr.employees e
   GROUP BY e.department_id;

Example 3:
 XMLAGG: Generating Nested Elements
Function XMLAgg can be used to reflect the hierarchical nature of some relationships that exist in tables. This example generates a department element for department 30. Within this element is a child element for each employee of the department. Within each employee element is a dependent element for each dependent of that employee.
First, this query shows the employees of department 30.
SELECT last_name, employee_id FROM employees WHERE department_id = 30;

LAST_NAME                 EMPLOYEE_ID
------------------------- -----------
Raphaely                          114
Khoo                              115
Baida                             116
Tobias                            117
Himuro                            118
Colmenares                        119

6 rows selected.

A dependents table is created, to hold the dependents of each employee.
CREATE TABLE hr.dependents (id NUMBER(4) PRIMARY KEY,
                            employee_id NUMBER(4),
                            name VARCHAR2(10));
Table created.
INSERT INTO dependents VALUES (1, 114, 'MARK');
1 row created.
INSERT INTO dependents VALUES (2, 114, 'JACK');
1 row created.
INSERT INTO dependents VALUES (3, 115, 'JANE');
1 row created.
INSERT INTO dependents VALUES (4, 116, 'HELEN');
1 row created.
INSERT INTO dependents VALUES (5, 116, 'FRANK');
1 row created.
COMMIT;
Commit complete.

This query generates the XML data for department that contains the information on dependents (the actual output is not pretty-printed):
SELECT
  XMLElement(
    "Department",
    XMLAttributes(d.department_name AS "name"),
    (SELECT
       XMLAgg(XMLElement("emp",
                         XMLAttributes(e.last_name AS name),
                         (SELECT XMLAgg(XMLElement("dependent",
                                        XMLAttributes(de.name AS "name")))
                            FROM dependents de
                            WHERE de.employee_id = e.employee_id)))
       FROM employees e
       WHERE e.department_id = d.department_id)) AS "dept_list"
  FROM departments d
  WHERE department_id = 30;

output
--------------------------------------------------------------------------------

 
   
    dept_list
--------------------------------------------------------------------------------
.


1 row selected in xml format it not showing in blog due to xml format ...

Function XMLElement

 XMLElement to construct XML instances from relational data. It takes as arguments an element name, an optional collection of attributes for the element, and zero or more additional arguments that make up the element content. It returns an XMLType instance.
Example 1:
Formatting a Date
This example shows how to produce an XML date with a format different from the XML Schema standard format.
-- With standard XML date format:
SELECT XMLElement("Date", hire_date)
  FROM hr.employees
  WHERE employee_id = 203;

Example 2:
-- With an alternative date format:
SELECT XMLElement("Date", to_char(hire_date))
  FROM hr.employees
  WHERE employee_id = 203;


Example 3:
 Generating an Element for Each Employee
This example produces an Emp element for each employee, with the employee name as its content:
SELECT e.employee_id,
       XMLELEMENT ("Emp", e.first_name ||' '|| e.last_name) AS "RESULT"
   FROM hr.employees e
   WHERE employee_id > 200;

Example 4:
 Generating Nested XML
To produce an Emp element for each employee, with elements that provide the employee name and hire date, do the following:
SELECT XMLElement("Emp",
                   XMLElement("name", e.first_name ||' '|| e.last_name),
                   XMLElement("hiredate", e.hire_date)) AS "RESULT"
FROM hr.employees e
WHERE employee_id > 200 ;

Example 5:
Generating Employee Elements with ID and Name Attributes
This example produces an Emp element for each employee, with an id and name attribute:
SELECT XMLElement("Emp", XMLAttributes(
                           e.employee_id as "ID",
                           e.first_name ||' ' || e.last_name AS "name"))
  AS "RESULT"
  FROM hr.employees e
  WHERE employee_id > 200;

Example 6:
As mentioned in "Escaping Characters in Generated XML Data", characters in the root-element name and the names of any attributes defined by AS clauses are not escaped. Characters in an identifier name are escaped only if the name is created from an evaluated expression (such as a column reference). The following query shows that the root-element name and the attribute name are not escaped. Invalid XML is produced because greater-than sign (>) and a comma (,) are not allowed in XML element and attribute names.
SELECT XMLElement("Emp->Special",
                  XMLAttributes(e.last_name || ', ' || e.first_name
                                AS "Last,First"))
   AS "RESULT"
   FROM hr.employees e
   WHERE employee_id = 201;

Example 7:
Using Namespaces to Create a Schema-Based XML Document
This example illustrates the use of namespaces to create an XML schema-based document. Assuming that an XML schema "http://www.oracle.com/Employee.xsd" exists and has no target namespace, then the following query creates an XMLType instance conforming to that schema:
SELECT XMLElement("Employee",
                  XMLAttributes('http://www.w3.org/2001/XMLSchema' AS
                                  "xmlns:xsi",
                                'http://www.oracle.com/Employee.xsd' AS
                                  "xsi:nonamespaceSchemaLocation"),
                  XMLForest(employee_id, last_name, salary)) AS "RESULT"
   FROM hr.employees
   WHERE department_id = 10;

Example 7:
Generating an Element from a User-Defined Datatype Instance
Example  shows an XML document with employee information. You can generate a hierarchical XML document with the employee and department information as follows:
CREATE OR REPLACE TYPE emp_t AS OBJECT ("@EMPNO" NUMBER(4),
                                         ENAME VARCHAR2(10));
/
Type created.

CREATE OR REPLACE TYPE emplist_t AS TABLE OF emp_t;
/
Type created.

CREATE OR REPLACE TYPE dept_t AS OBJECT ("@DEPTNO" NUMBER(2),
                                         DNAME VARCHAR2(14),
                                         EMP_LIST emplist_t);
/
Type created.

SELECT XMLElement("Department",
                  dept_t(department_id,
                         department_name,
                         CAST(MULTISET(SELECT employee_id, last_name
                                         FROM hr.employees e
                                         WHERE e.department_id = d.department_id)
                              AS emplist_t)))
  AS deptxml
  FROM hr.departments d
  WHERE d.department_id = 10;

 

Function XMLTable in Oracle 10g

The function XMLTABLE is used to translate an xml object into separated fields. But you
probably want to construct a table with xml content, which is different.
You can create a table with an extra column that contains xml content

1. CREATE TABLE mytable (my_id NUMBER PRIMARY KEY, my_xml XMLType);

2.
INSERT INTO mytable VALUES (1,xmltype(''));

3. SELECT my_id
      ,my_xml.extract('/myxml@id').getstringval()
from mytable
Finished.
---error


So you actually do want to use the XMLTABLE function, Your error indicates that you are not
getting the file at all. So you need to craft your url to load it correctly. A test case I
constructed with embedded xml is:
  SELECT seq
       , id
        , content
 FROM XMLTABLE('/xml/myrec'
        PASSING XMLType('

Output is:
 SEQ ID    CONTENT
---- ----- --------------------
   1 D12   hello1
   2 D13   hello2

SELECT person_id
FROM person_data a, XMLtable('for $root in $date
return $root/pdrecord/PDDOB/text()'
passing a.person_data as "date")t
/

 SELECT * FROM XMLTABLE(
     'ora:view("PERSON_DATA")/ROW/PERSON_ID,/ROW/PERSON_DATA')

SELECT XMLQuery(
     'ora:view("DEPARTMENTS")'
  RETURNING CONTENT) AS EMP_DEPARTMENTS
 FROM dual
/



OraApps Search

Custom Search

Search This Blog