2015-08-23 123 views
1

試圖使用2個表格進行查詢,但顯然我對第二個表格選擇不合適INTO s。我可以在這裏甚至使用UNION ALL聲明,或者我怎樣做INNER JOIN聲明?我的代碼示例如下:UNION或INNER JOIN PL/SQL查詢

DECLARE 
v_CVar1 NUMERIC(1); 
v_CVar2 CHAR(4); 
v_SVar1 NUMERIC(1); 
v_SVar2 CHAR(4); 

BEGIN 
SELECT CVAR1, CVAR2 
INTO v_CVar1, v_CVar2 
FROM CUSTOMER 
WHERE CVAR1 = 5 
UNION ALL 
SELECT SVAR1, SVAR2 
INTO v_SVar1, v_SVar2 
FROM SALESMAN; 

DBMS_OUTPUT.PUT_LINE('Example ' || v_CVar1 || ' ' || v_SVar2); 

END; 

回答

1

你不能這樣做。

你可以做的是:

SELECT CVAR1, CVAR2 
INTO v_CVar1, v_CVar2 
FROM CUSTOMER 
WHERE CVAR1 = 5; 

SELECT SVAR1, SVAR2 
INTO v_SVar1, v_SVar2 
FROM SALESMAN; 

此外,不要使用numericchar,它是更好的使用numbervarchar2,而是如果你有一個選擇。

如果你還想用union來做,你首先需要使用數組,例如, dbms_sql.varchar2adbms_sql.number_table數據類型相應的(或創建您的類型),並且只使用一個bulk collect into條款:

SELECT CVAR1, CVAR2 
BULK COLLECT INTO array1, array2 
FROM CUSTOMER 
WHERE CVAR1 = 5 
UNION ALL 
SELECT SVAR1, SVAR2 
FROM SALESMAN; 
0

你可以試試這個:

create table customer (
cus_id number(5), 
cust_name varchar2(20) 
); 

insert into customer values(1,'Mahi'); 
insert into customer values(2,'Raja'); 

DECLARE 
v_CVar1 VARCHAR2(10); 
v_CVar2 VARCHAR2(10); 
Cursor C1 is 
SELECT cus_id, cust_name FROM customer 
UNION ALL 
SELECT cus_id, cust_name FROM customer; --Change table name 
BEGIN 
For rec in C1 
Loop 
v_CVar1 := rec.cus_id; 
v_CVar2 := rec.cust_name; 
DBMS_OUTPUT.PUT_LINE('Example : ' || ' ' || v_CVar1 || ' ' || v_CVar2); 
End Loop; 
END; 

OUTPUT:

Example : 1 Mahi 
Example : 2 Raja 
Example : 1 Mahi 
Example : 2 Raja 

Statement processed.