如何使 Oracle ALTER TABLE MODIFY 脚本是幂等的?
How to make Oracle ALTER TABLE MODIFY script be idempotent?
我有这个迁移脚本;
ALTER TABLE table_name MODIFY (column_name NULL);
如何使其幂等?
您可以使用异常处理程序:
DECLARE
CANNOT_MODIFIY_TO_NULL EXCEPTION;
PRAGMA EXCEPTION_INIT(CANNOT_MODIFIY_TO_NULL, -1451);
BEGIN
EXECUTE IMMEDIATE 'ALTER TABLE TABLE_NAME MODIFY (column_name NULL)';
exception
when CANNOT_MODIFIY_TO_NULL then
NULL;
END;
或在视图 USER_TAB_COLUMNS
:
中检查 NULLABLE
DECLARE
CURSOR Cols IS
SELECT COLUMN_NAME
FROM USER_TAB_COLUMNS
WHERE TABLE_NAME = 'TABLE_NAME'
AND NULLABLE = 'N'
AND COLUMN_NAME = 'COLUMN_NAME';
BEGIN
FOR aCol IN Cols LOOP
EXECUTE IMMEDIATE 'ALTER TABLE TABLE_NAME MODIFY ('||aCol.COLUMN_NAME||' NULL)';
END LOOP;
END;
我有这个迁移脚本;
ALTER TABLE table_name MODIFY (column_name NULL);
如何使其幂等?
您可以使用异常处理程序:
DECLARE
CANNOT_MODIFIY_TO_NULL EXCEPTION;
PRAGMA EXCEPTION_INIT(CANNOT_MODIFIY_TO_NULL, -1451);
BEGIN
EXECUTE IMMEDIATE 'ALTER TABLE TABLE_NAME MODIFY (column_name NULL)';
exception
when CANNOT_MODIFIY_TO_NULL then
NULL;
END;
或在视图 USER_TAB_COLUMNS
:
NULLABLE
DECLARE
CURSOR Cols IS
SELECT COLUMN_NAME
FROM USER_TAB_COLUMNS
WHERE TABLE_NAME = 'TABLE_NAME'
AND NULLABLE = 'N'
AND COLUMN_NAME = 'COLUMN_NAME';
BEGIN
FOR aCol IN Cols LOOP
EXECUTE IMMEDIATE 'ALTER TABLE TABLE_NAME MODIFY ('||aCol.COLUMN_NAME||' NULL)';
END LOOP;
END;