create or replace procedure Audit_procedure
as
v_Chunk number(10) := 20000;
v_PrepareStmt nvarchar(20000);
v_InsertStmt nvarchar(20000);
v_SelectStmt nvarchar(20000);
v_DeleteStmt nvarchar(20000);
v_UpdateStmt nvarchar(20000);
v_TempStmt nvarchar(20000);
v_Columns NVARCHAR(20000);
-查询的动态对象
v_Audit_DB nvarchar2(20):= 'Bell_Audit';
v_SO_DB nvarchar2(20) :='Bell_kat_4';
v_InsertTbl nvarchar2(20):='W6Audit_History';
v_SelectTbl nvarchar2(20):='W6Audit';
begin
-创建临时w6key表
IF OBJECT_ID('tempdb..#TempW6key') IS NOT NULL THEN
execute immediate ' drop TABLE #TempW6key';
END IF;
BEGIN
EXECUTE IMMEDIATE 'CREATE TABLE #TempW6key (W6key number(10) NOT NULL),
CONSTRAINT W6PK PRIMARY KEY(
W6Key
); ON [PRIMARY]
END;'
-准备用于插入选择语句的列
v_PrepareStmt :=N'
SELECT @Columns=@Columns+''[''+SO.COLUMN_NAME+''],''
FROM '||v_SO_DB||'.INFORMATION_SCHEMA.COLUMNS SO
INNER JOIN
'||v_Audit_DB||'.INFORMATION_SCHEMA.COLUMNS AUDIT
ON SO.COLUMN_NAME=AUDIT.COLUMN_NAME
WHERE SO.TABLE_NAME = N'''||v_SelectTbl||'''
AND AUDIT.TABLE_NAME = N'''||v_InsertTbl||'''';
EXECUTE IMMEDIATE SP_EXECUTESQL; v_PrepareStmt,
N'@Columns NVARCHAR(MAX)='''' OUTPUT', v_Columns=v_Columns OUTPUT
v_Columns :=SUBSTR(v_Columns, 1, LENGTH(RTRIM(v_Columns)) - 1);
END TRY
BEGIN CATCH
PRINT 'ERROR ON COLUMNS BUILD'
RAISERROR ( '', 10, 1) WITH NOWAIT;
RETURN;
END CATCH
-准备所有语句
v_TempStmt:= 'INSERT INTO #TempW6key (W6Key)
SELECT W6Key FROM ['||v_SO_DB||'].[dbo].['||v_SelectTbl||'] WITH(NOLOCK)';
-创建临时w6keys表以从Audit移至Audit_History
v_InsertStmt:='INSERT INTO ['||v_Audit_DB||'].[dbo].['||v_InsertTbl||']
('||v_Columns||')'; -- Insert into Audit History statment part 1
v_SelectStmt:='SELECT '||v_Columns||' FROM ['||v_SO_DB||'].[dbo].['||v_SelectTbl||']
WITH(NOLOCK)
WHERE W6Key IN (SELECT W6Key FROM #TempW6key WITH(NOLOCK))';
-插入“审核历史记录”声明的第2部分
v_DeleteStmt:='DELETE FROM ['||v_SO_DB||'].[dbo].['||v_SelectTbl||']
WHERE W6Key IN (SELECT W6Key FROM #TempW6key WITH(NOLOCK))'; -- Delete archived records older than 1 day from Audit
-执行所有语句
/* BEGIN TRANSACTION */; toAuditHistory
BEGIN TRY
-语句执行开始
SET ROWCOUNT v_Chunk
EXECUTE IMMEDIATE v_TempStmt;
EXECUTE IMMEDIATE v_InsertStmt||v_SelectStmt;
EXECUTE IMMEDIATE v_DeleteStmt;
-语句执行结束
COMMIT TRANSACTION; toAuditHistory;
END TRY
BEGIN CATCH
RAISERROR ( 'Iteration Failed, Rolling back', 10, 1) WITH NOWAIT;
ROLLBACK TRANSACTION toAuditHistory;
RETURN;
END CATCH.
end;