Oraclewith statement usage

Source: Internet
Author: User
Psoug.orgreferencewith.htmlwww.oracle-base.comarticlesmiscwith-clause.phpgennick.comwith.html ------ UnderstandingtheWITHClaus reference: ishare.iask.sina.com.cnf21674385.html

Http://psoug.org/reference/with.html http://www.oracle-base.com/articles/misc/with-clause.php http://gennick.com/with.html ------ Understanding the WITH Claus references: http://ishare.iask.sina.com.cn/f/21674385.html

Reference URL: http://psoug.org/reference/with.html

Http://www.oracle-base.com/articles/misc/with-clause.php

Http://gennick.com/with.html ------ Understanding the WITH Claus

Reference: http://ishare.iask.sina.com.cn/f/21674385.html

The WITH query_name clause lets you assign a name to a subquery block. you can then reference the subquery block multiple places in the query by specifying the query name. oracle optimizes the query by treating the query name as either an inline view or as a temporary table.
(WITH statements can only be at the top of a statement)
You can specify this clause in any top-level SELECT statement and in most types of subqueries. the query name is visible to the main query and to all subsequent subqueries beyond t the subquery that defines the query name itself.

A with clause is really best used when the result of the WITH query is required more than one time in the body of the query such as where one averaged value needs to be compared against two or three times.

Restrictions on Subquery Factoring:

  • You cannot nest this clause. that is, you cannot specify the subquery_factoring_clause within the subquery of another subquery_factoring_clause. however, a query_name defined in one subquery_factoring_clause can be used in the subquery of any subsequent subquery_factoring_clause. (The WITH statement cannot be nested. The WITH statement defined earlier can be used in any WITH statement after it)
  • In a query with set operators, the set operator subquery cannot contain the subquery_factoring_clause, but the FROM subquery can contain the subquery_factoring_clause

With statement syntax (AS parentheses cannot be left blank)

1 WITH 
 
   AS (subquery_sql_statement)2 SELECT 
  
    FROM 
   
    ;
   
  
 

Simple with statement:

WITH A AS (SELECT * FROM DUAL)SELECT * FROM A

Note that the WITH statement must be used in subsequent queries; otherwise, an error message is displayed:

1 WITH A AS2  (SELECT * FROM DUAL)3 SELECT * FROM dual

(The error occurs because the defined WITH statement is not used for query)

Syntax of two with statements:

1 WITH 
 
   AS 2   (subquery_sql_statement),3      
  
    AS4   (sql_statement_from_alias_one)5 SELECT 
   
    6 FROM 
    
     , 
     
      7 WHERE 
      
       ;
      
     
    
   
  
 

Test example:

1 WITH A AS2  (SELECT * FROM DUAL),3 B AS4  (SELECT * FROM DUAL)5 SELECT * FROM B, A

If not all the defined WITH statements are used after the FROM key subscriber, the same error message is displayed:

(Queries scheduled in the with clause cannot be referenced)

Use the WITH statement to connect to the View:

1 CREATE OR REPLACE VIEW WITH_V AS2   WITH DEPT_V AS (SELECT * FROM DEPT),3    EMP_V AS (SELECT * FROM EMP)4    SELECT D.DNAME,D.LOC,E.* FROM EMP_V E5    LEFT JOIN DEPT_V D6    ON D.DEPTNO = E.DEPTNO

You can use the with as statement to define a name for the subquery statement block. You can use this subquery name to reference this subquery in many places of the query statement. Oracle databases treat referenced subquery names like inline views or temporary tables, so as to play an optimized role. The with clause is the new syntax of 9i. You can use the subquery definition clause before any top-level SELECT statement and almost all types of subquery statements. The defined subquery name can be referenced in the primary query statement and all subquery statements, but cannot be referenced before being undefined. With clause cannot be nested <也就是with子句中不能有with子句> But the "subquery definition" statement in the subquery can reference the defined subquery name. <可以引用前面已经定义的with子句>

Summary of the WITH clause:

1. When there are multiple query definitions before the select statement of the same level, 1st queries are separated by commas.

2. There cannot be a comma between the last with clause and the following query, which is separated only by right brackets. The query of the with clause must be enclosed by parentheses.

3. If the with clause is defined and is not used in the query, A ora-32035 error is reported: the query name defined in the with clause is not referenced. (At least one with query name is not referenced, and the solution is to remove the with query that is not referenced.) Note: as long as there is a reference to it, it is not necessarily required to be referenced in the main query, for example, the with query is also referenced.

4. the query defined by the with clause can be used in the with clause. However, a with clause cannot be nested inside it.

5. The result column of the with query has an alias. the alias or * must be used for reference *.

WITH statement advantages:

(1). enhanced SQL readability. For example, get a meaningful name for a specific with subquery.

(2) The with subquery is executed only once and the results are stored in the user's temporary tablespace. It can be referenced multiple times to improve performance.

For example, when importing an EXCEL file, you sometimes need to store the data in a temporary table. Currently, when importing the file, you can clear the data in the temporary table, if concurrency problems occur, the two users may operate on the data of the other party separately, which may cause confusion. However, you can use the WITH function and the UNION statement to splice an SQL statement and store it in the SESSION, when you need to export error information, you can use this statement to construct data.

--------------------------- Use example of the WITH statement:

1. Check that the total salary of the Department is greater than the average total salary of all departments. Department table s_dept and employee table s_emp. Analysis: To do this query, you must first calculate the total salary of all departments and then calculate the average salary of the total salary, then, find out the departments whose total salaries are higher than the average total salaries of all departments. Then the total salary of all departments can be found in step 1 with query, and the average salary can be found in the result table obtained in step 2 with query, the result of comparing the total salary with the average salary is as follows:

1 WITH DEPT_COSTS AS -- query the total salary of the Department 2 (select d. DNAME, SUM (E. SAL) DEPT_TOTAL 3 from dept d, emp e 4 where e. DEPTNO = D. DEPTNO 5 group by d. DNAME), 6 AVE_COST AS -- query the average salary of a department. In the next WITH statement, you can reference the WITH statement 7 (select sum (DEPT_TOTAL)/COUNT (*) defined previously (*) AVG_SUM FROM DEPT_COSTS) 8 SELECT * 9 FROM DEPT_COSTS DC10 where dc. DEPT_TOTAL> (select ac. AVG_SUM FROM AVE_COST AC) -- compare

2. You can use the preceding data and directly reference it in the with statement. Requirement: displays the data queried Based on the query results, and makes statistics based on the query results, such as the maximum salary, minimum salary, and average salary,

Perform cascade operations. because the number of queried statistical data records is one, there will be no errors in the flute product,

1 WITH TEMP_DATA AS -- Query basic data 2 (select empno, ENAME, JOB, MGR, HIREDATE, SAL, COMM, deptno from emp ), 3 TEM_SUM AS -- Query statistical data 4 (select max (SAL), MIN (SAL), SUM (SAL) FROM TEMP_DATA) 5 SELECT * 6 FROM TEM_SUM, TEMP_DATA -- cascade, because the number of statistics queried is one, the error of the flute product will not occur.

3. The with subquery cannot be nested, but the with definition can reference the previous result set.

1 WITH SELECT_TRADE AS2 (SELECT TRADE_ID from product where id = 1 ), 3 -- The with subquery can reference the previous result 4 SELECT_TRADEMARK AS5 (select name from trademark where id = (SELECT TRADE_ID FROM SELECT_TRADE) 6 SELECT * FROM SELECT_TRADEMARK;

The following statement is incorrect: nesting with statements is not allowed

1 -- this statement Error 2 WITH SELECT_TRADE AS3 -- with has nested with, not allowed 4 (with temp AS5 (SELECT TRADE_ID from product where id = 1) 6 SELECT TRADE_ID from temp ), 7 SELECT_TRADEMARK AS8 (select name from trademark where id = (SELECT TRADE_ID FROM SELECT_TRADE) 9 SELECT * FROM SELECT_TRADEMARK;

4. A complex WITH statement example: Use WITH in a subquery,

1 select a, B 2 FROM (3 -- 1st definitions t_with 4 WITH T_WITH AS (SELECT '1' A FROM DUAL) 5 -- The subquery uses t_with 6 SELECT X. a, 7 (8 -- internally defines t_with_z, and uses t_with 9 WITH T_WITH_Z AS (SELECT '1' a from T_WITH) 10 SELECT S_1.A11 FROM T_WITH_Z S_1, T_WITH S_2) b12 FROM T_WITH X, 13 -- use t_with in the subquery, and define t_with_y14 (WITH T_WITH_Y AS (SELECT '1' a from T_WITH) 15 SELECT F_1.A16 FROM T_WITH_Y F_1, t_WITH F_2) Y17 where x. A = Y. a18 -- Define t_with_x19 and x. A = (WITH T_WITH_X AS (SELECT '1' A20 FROM T_WITH) 21 SELECT W_1.A22 FROM T_WITH_X W_1, T_WITH W_2 ))

5. Reference The WITH function in the column subquery:

1 SELECT (WITH A AS (SELECT '1' FROM DUAL)2          SELECT * FROM A) FROM DUAL

6. Reference WITH query results:

1 SELECT *2   FROM (WITH A AS (SELECT '1' FROM DUAL)3          SELECT * FROM A)

7. For a query, if the result row of the query is not a multiple of 5, fill in the blank line until the number of queried rows is a multiple of 5.

1 WITH TEMP_DATA AS2  (SELECT (5 - MOD(COUNT(*), 5)) COUNTS FROM DUAL CONNECT BY LEVEL < 3)3 SELECT '1', '1'4   FROM DUAL5 UNION ALL6 SELECT NULL, NULL FROM DUAL CONNECT BY LEVEL < (SELECT * FROM TEMP_DATA)

You can also use ALL_OBJECTS

WITH TEMP_DATA AS (SELECT (5 - MOD(COUNT(*), 5)) COUNTS FROM DUAL CONNECT BY LEVEL < 3)SELECT '1', '1'  FROM DUALUNION ALLSELECT NULL, NULL FROM ALL_OBJECTS WHERE ROWNUM < (SELECT * FROM TEMP_DATA)

Query results:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.