4.4. Getting a Sequence Value from Oracle
Problem
When you add a
row
into an Oracle table that uses a sequence to generate the value for a
primary key column, the value assigned to the column in the
DataTable is replaced by a value generated by the
database. You need to retrieve the new value to keep the
DataTable synchronized with the database.
Solution
Use Oracle’s
CURRVAL
and NEXTVAL keywords.
The sample code executes a stored procedure to insert a record into an Oracle table and uses the output parameter of the stored procedure to return the sequence value generated for the primary key column. The sequence value for the new record is displayed.
The sample uses a single stored procedure:
SP0404_INSERTUsed to add a new record into table
TBL0404. The primary key field value is generated by the Oracle sequenceTBL0404_SEQUENCEand is returned in the output parameterpID.
The sample uses one sequence:
TBL0404_SEQUENCECalled by the stored procedure
SP0404_INSERTto generate unique, sequential values for the primary key fieldIDin the tableTBL0404.
The Oracle stored procedure is shown here in Example 4-5.
Example 4-5. Stored procedure: SP0404_Insert
CREATE PROCEDURE SP0404_INSERT
(
pID out number,
pFIELD1 nvarchar2,
pFIELD2 nvarchar2
)
as
begin
INSERT INTO TBL0404 (
ID,
FIELD1,
FIELD2)
VALUES (
TBL0404_SEQUENCE.NEXTVAL,
pFIELD1,
pFIELD2
);
SELECT TBL0404_SEQUENCE.CURRVAL INTO pID FROM DUAL;
end;The Oracle sequence is shown here in Example 4-6.
Example 4-6. Sequence: TBL0404_Sequence
CREATE ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access