I made this function but it return an error when i execute it!
create or replace function get_accounts
(Acc_id in Account1.account_id%Type)
return account1%rowtype
as
l_cust_record account1%rowtype;
begin
select * into l_cust_record from account1
where account_id=Acc_id;
return(l_cust_record);
end;
/
In Oracle, function which returns record set, requires an object type with attributes to be created first. Once object Type is created, we have to create named table type of the object type. In function we can use named table type as return type.
An Oracle PL/SQL procedure can have several OUT variables to return multiple values. If you are looking for database table, user REF CURSOR as return type or OUT parameter of a procedure. On other hand if you are looking for a memory table, define a TABLE type and use it as the return type or OUT parameter.
The %ROWTYPE attribute is used to define a record with fields corresponding to all of the columns that are fetched from a cursor or cursor variable. Each field assumes the data type of its corresponding column. The %ROWTYPE attribute is prefixed by a cursor name or a cursor variable name.
The %ROWTYPE attribute provides a record type that represents a row in a database table. The record can store an entire row of data selected from the table or fetched from a cursor or cursor variable. Variables declared using %ROWTYPE are treated like those declared using a datatype name.
Oracle Setup:
CREATE TABLE account1 (
account_id INT,
name VARCHAR2(20)
);
INSERT INTO account1 VALUES ( 1, 'Bob' );
CREATE OR REPLACE FUNCTION get_accounts(
Acc_id IN Account1.account_id%TYPE
) RETURN account1%ROWTYPE
AS
l_cust_record account1%ROWTYPE;
BEGIN
SELECT *
INTO l_cust_record
FROM account1
WHERE account_id = Acc_id;
RETURN l_cust_record;
END;
/
PL/SQL Block:
DECLARE
r_acct ACCOUNT1%ROWTYPE;
BEGIN
r_acct := get_accounts( 1 );
DBMS_OUTPUT.PUT_LINE( r_acct.name );
END;
/
Output:
Bob
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With