我有一个由程序代码填充的数据登台表。
TABLE BatchRecord{
BatchRecordID NUMBER PRIMARY KEY,
BatchID NUMBER, --Assigned by the procedural code
RecordID NUMBER, --Relative to the batch
FieldID NUMBER, --Assigned by the procedural code; FK to another table
Value VARCHAR2(MAX)
Instance NUMBER}
然后需要将每个BatchRecord转换为三个相关的表:Records,RecordFields,FieldValues。
TABLE Record{
RecordID NUMBER PRIMARY KEY,
BatchID NUMBER, --Same from BatchRecords}
TABLE RecordFields{
RecordFieldID NUMBER PRIMARY KEY,
RecordID NUMBER, --FK from Records
FieldID NUNBER --Same from BatchRecords}
TABLE FieldValues{
RecordFieldID NUMBER PRIMARY KEY,
Instance NUMBER PRIMARY KEY, --Same from BatchRecords
Value VARCHAR2(MAX) --Same from BatchRecords}
在SQL Server中,我可以使用MERGE
语句并使用OUTPUT
捕获新插入的键来完成此操作:
CREATE TABLE #InsertedRecords(RecordID INT, NewRecordID INT);
MERGE INTO Records USING (
SELECT RecordID
FROM BatchRecords
WHERE BatchID = @BatchID
GROUP BY RecordID) AS BR ON 1 = 0
WHEN NOT MATCHED THEN
INSERT (BatchID)
VALUES (@BatchID)
OUTPUT BR.RecordID, INSERTED.RecordID INTO #InsertedRecords;
采用类似的方法插入RecordFields,并使用INSERT...SELECT
语句插入FieldValues。
但是,在Oracle中,无法在RETURNING
语句中使用OUTPUT
(相当于MERGE
),甚至不能在SELECT...INTO
语句中使用。{ / p>
是否有可能在Oracle中完成相同任务,同时避免FORALL
循环,因为BatchRecords的总数可能超过数百万?
答案 0 :(得分:0)
您可以尝试使用oracle PIPELINE函数从BatchRecord中选择所有记录,然后将行管道输入到不同的表中。如果需要,我可以展示一个例子。
修改强>
create or replace package test_pkg AS
TYPE REP_CURS IS REF CURSOR;
TYPE output_REC IS RECORD(
RecordID_ number,
BatchID_ number);
TYPE output_TAB IS TABLE OF output_REC;
FUNCTION Get_Data RETURN output_TAB
PIPELINED;
END test_pkg;
CREATE OR REPLACE PACKAGE BODY test_pkg IS
FUNCTION Get_Data RETURN output_TAB
PIPELINED IS
output_REC_ output_REC;
rep_lines_ REP_CURS;
stmt_ VARCHAR2(5000);
table_rec_ BatchRecord%ROWTYPE;
begin
stmt_ := ' (select BatchRecordID,BatchID ....Instance from BatchRecord) ';
OPEN rep_lines_ FOR stmt_;
LOOP
FETCH rep_lines_
INTO table_rec_;
EXIT WHEN rep_lines_%NOTFOUND;
output_REC_.RecordID_ := <<whatever valu that you want>;
output_REC_.BatchID_ := table_rec_.BatchID;
PIPE ROW(output_REC_);
END LOOP;
CLOSE rep_lines_;
RETURN;
exception
when others then
DBMS_OUTPUT.put_line('Error:' || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE ||
DBMS_UTILITY.FORMAT_ERROR_STACK ||
DBMS_UTILITY.FORMAT_CALL_STACK);
END Get_Data;
END test_pkg;
我已经展示了插入Record的示例。你必须对其他两个表做类似的事情。希望这会有所帮助!!