我必须使用PL / SQL中的函数实现经典的数字交换程序(从用户接收两个数字值并显示它们交换)。但是,我似乎无法使用PL / SQL中的函数返回两个数字。我想知道是否有任何方法可以从PL / SQL中的函数返回两个值,或者是否有其他方法可以完全编写此代码?
SET SERVEROUTPUT ON;
DECLARE
a NUMBER;
b NUMBER;
FUNCTION numSwap(num1 IN OUT NUMBER ,num2 IN OUT NUMBER )IS
temp_num NUMBER;
BEGIN
temp_num := num1;
num1 := num2;
num2 := temp;
END;
BEGIN
a := &a;
b := &b;
DBMS_OUTPUT.PUT_LINE('First Number = ' || a);
DBMS_OUTPUT.PUT_LINE('Second Number = ' || b);
--After swapping values
DBMS_OUTPUT.PUT_LINE('After swapping the values');
numSwap(a,b);
--Displaying the results
DBMS_OUTPUT.PUT_LINE('First Number = ' || a);
DBMS_OUTPUT.PUT_LINE('Second Number = ' || b);
END;
编辑:为了澄清,我意识到这或多或少是一个过程的语法,但我想知道是否有任何方法使用函数执行相同的程序
答案 0 :(得分:2)
阐述MT0的例子......
函数只返回一个值。您可以通过使用包含两个值的记录(或可能是集合)来解决它。请注意,记录类型仅在PLSQL块的范围内声明。
declare
a number;
b number;
type two_numbers is record(
a number,
b number);
l_two_numbers two_numbers;
function swap(p_two_numbers two_numbers) return two_numbers is
l_return two_numbers;
begin
l_return.a:=p_two_numbers.b;
l_return.b:=p_two_numbers.a;
return l_return;
end;
begin
a := &a;
b := &b;
l_two_numbers.a:=a;
l_two_numbers.b:=b;
dbms_output.put_line('First Number = ' || l_two_numbers.a);
dbms_output.put_line('Second Number = ' || l_two_numbers.b);
l_two_numbers := swap(l_two_numbers);
dbms_output.put_line('First Number = ' || l_two_numbers.a);
dbms_output.put_line('Second Number = ' || l_two_numbers.b);
end;
答案 1 :(得分:0)
使用程序:
DECLARE
a NUMBER;
b NUMBER;
PROCEDURE numSwap(num1 IN OUT NUMBER ,num2 IN OUT NUMBER )
IS
temp_num NUMBER := num1;
BEGIN
num1 := num2;
num2 := temp_num;
END;
BEGIN
a := &a;
b := &b;
DBMS_OUTPUT.PUT_LINE('First Number = ' || a);
DBMS_OUTPUT.PUT_LINE('Second Number = ' || b);
numSwap(a,b);
DBMS_OUTPUT.PUT_LINE('First Number = ' || a);
DBMS_OUTPUT.PUT_LINE('Second Number = ' || b);
END;
/
答案 2 :(得分:0)
如果你想仍然调用一个函数你可以使用oracle type
(如果你需要在SELECT中使用:试试下面的
set serveroutput on
create or replace type t_swap
is object(first_number number, second_number number);
/
create or replace
function f_num_swap(p_first_number in number, p_second_number in number) return t_swap
is
v_swap t_swap;
begin
v_swap := t_swap(p_second_number, p_first_number);
return v_swap;
end;
/
-- You can access from select
select f_num_swap(1, 2).first_number, f_num_swap(1, 2).second_number from dual;
-- Or you can access from PL/SQL block
declare
v_swap t_swap;
begin
v_swap := f_num_swap(1, 2);
dbms_output.put_line('First Nubmer Swapped: '||v_swap.first_number);
dbms_output.put_line('Second Nubmer Swapped: '||v_swap.second_number);
end;
/