Home > Database > Mysql Tutorial > 详解如何在Oracle中连接输出结果

详解如何在Oracle中连接输出结果

WBOY
Release: 2016-06-07 16:54:20
Original
846 people have browsed it

但是也可能遇到需要下面这样的结果。department enamepurchasing raphely,khoo,baida,tobias,himuro,colmenaresit hunol

一个偶然的机会,看到ASK TOM上的一个问题(?p=100:11:0::::P11_QUESTION_ID:229614022562),是关于查询结果字符串连接的。下图是对一个视图(视图代码附后,全部操作是在Oracle 10g中的HR schema中完成的)进行查询得到的常见的结果。

department enamemarketing  hartstein

marketing  fay

purchasing raphaely

purchasing khoo

...

it         hunold

it         ernst

...

但是也可能遇到需要下面这样的结果。

department enamepurchasing raphely,khoo,baida,tobias,himuro,colmenares

it         hunold,ernst,austin,pataballa,lorentz

marketing  hartstein,fay

CREATEORREPLACEVIEWd_employeeAS

SELECTd.department_name department,

e.last_name ename

FROMdepartments d,

employees e

WHEREd.department_id = e.department_idAND

d.department_nameIN('IT','Marketing','Purchasing');

为此,Tom大师提供了两种解决方案,如下:

方法一:

使用静态的SQL从表中选出需要进行连接的所有数据。

CREATEORREPLACEFUNCTIONCONCAT(P_DEPINVARCHAR2)RETURNVARCHAR2IS

L_STRVARCHAR2(200)DEFAULTNULL;

L_SEPVARCHAR2(200)DEFAULTNULL;

BEGIN

FORRCIN(SELECTENAMEFROMD_EMPLOYEEWHEREDEPARTMENT = P_DEP)LOOP

L_STR := L_STR || L_SEP || RC.ENAME;

L_SEP :=',';

ENDLOOP;

RETURNL_STR;

END;

使用下列查询语句查询:

SELECTd.department, hr.concat(d.department) employeesFROMd_employee d

GROUPBYdepartment;

方法二:

使用动态SQL,传入关键列(需求中的department)和那一列的一个值,以及需要实际进行连接的列(需求中的ename)以及表。

CREATEORREPLACEFUNCTIONCONCAT2(P_KEY_NAME      INVARCHAR2,

P_KEY_VAL       INVARCHAR2,

P_OTHER_COL_NAMEINVARCHAR2,

P_TNAME         INVARCHAR2)

RETURNVARCHAR2AS

TYPERCISREFCURSOR;

L_STRVARCHAR2(4000);

L_SEPVARCHAR2(200);

L_VALVARCHAR2(4000);

L_CUR RC;

BEGIN

OPENL_CURFOR'select '|| P_OTHER_COL_NAME ||' from '|| P_TNAME ||' where '|| P_KEY_NAME ||' = :x '

USINGP_KEY_VAL;

LOOP

FETCHL_CUR

INTOL_VAL;

EXITWHENL_CUR%NOTFOUND;

L_STR := L_STR || L_SEP || L_VAL;

L_SEP :=',';

ENDLOOP;

CLOSEL_CUR;

RETURNL_STR;

END;

使用下列查询语句查询:

SELECTd.department, concat2('department', d.department,'ename','d_employee')FROMd_employee d

GROUPBYd.department;

Tom大师还提到,,如果你已经确切知道了需要连接显示的字段所包含的值的列表(比如,只包含A、T、L三个值),那么建议使用DECOD()方法。可以查看下面这个链接:?p=100:11:::::P11_QUESTION_ID:124812348063

linux

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template