Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do a function to return row type from a table in pl/sql?

Tags:

oracle

plsql

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;
/
like image 952
Sara Avatar asked Apr 07 '16 18:04

Sara


People also ask

How do you return a record type in a function?

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.

How do I return a table in PL SQL?

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.

What is row type in PL SQL?

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.

What is %type and %ROW type in PL SQL?

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.


1 Answers

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
like image 85
MT0 Avatar answered Sep 28 '22 03:09

MT0