DataGuard主从切换包括两种:
Switchover:主从状态正常,角色互切。切换后,DataGuard主从正常,可重新切回去。
Failover:主库down掉,备库切成主库,这种情况下DataGuard关系破坏,只能重新搭建

以下切换步骤来自Oracle 11g官方文档《Data Guard Concepts and Administration》。

1.DataGuard Swithover

1.1.验证主库是否可进行切换为备库

SQL> SELECT SWITCHOVER_STATUS FROM V$DATABASE;

SWITCHOVER_STATUS 
 ----------------- 
 TO STANDBY 
 1 row selected 

状态必须为TO STANDBY或 SESSIONS ACTIVE

1.2.在主库进行切换

SQL> ALTER DATABASE COMMIT TO SWITCHOVER TO PHYSICAL STANDBY WITH  SESSION SHUTDOWN;

1.3.关闭主库并启动到mount

SQL> SHUTDOWN ABORT;
SQL> STARTUP MOUNT;

1.4.验证备库可以切换角色

SQL> SELECT SWITCHOVER_STATUS FROM V$DATABASE;

SWITCHOVER_STATUS 
----------------- 
TO_PRIMARY 
1 row selected

状态必须是TO PRIMARY 或 SESSIONS ACTIVE

1.5.切换备库角色为PRIMARY

SQL> ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY WITH SESSION SHUTDOWN;

1.6.启动新主库

SQL> ALTER DATABASE OPEN;

1.7.在新备库启动同步

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE  DISCONNECT FROM SESSION;

1.8.在新备库查看同步状态

SQL>	select PROCESS,CLIENT_PROCESS,SEQUENCE# ,STATUS from v$managed_standby;

2.DataGuard Failover

Failover的前提是主库已经挂掉,必须启用备库来承担业务。

2.1.将未投递日志传输到备库

如果主库可以启动到mount,可以将未投递的redo和归档应用到备库。target_db_name 为备库的 DB_UNIQUE_NAME

SQL> ALTER SYSTEM FLUSH REDO TO target_db_name;

2.2.确认备库日志应用状态

SQL> SELECT UNIQUE THREAD# AS THREAD, MAX(SEQUENCE#) -
> OVER (PARTITION BY thread#) AS LAST from V$ARCHIVED_LOG;

    THREAD       LAST
---------- ----------
         1        100

手动应用日志

SQL> ALTER DATABASE REGISTER PHYSICAL LOGFILE 'filespec1';

检查日志是否全部应用

SQL> SELECT THREAD#, LOW_SEQUENCE#, HIGH_SEQUENCE# FROM V$ARCHIVE_GAP;

THREAD#    LOW_SEQUENCE# HIGH_SEQUENCE#
---------- ------------- --------------
         1            90             92

再次应用确实的日志

SQL> ALTER DATABASE REGISTER PHYSICAL LOGFILE 'filespec1';

2.3.停止日志同步

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;

2.4.应用所有日志

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE FINISH;

如果执行错误,可以用以下命令强制切换
SQL> ALTER DATABASE ACTIVATE PHYSICAL STANDBY DATABASE;

2.5.验证备库可以切换角色

SQL> SELECT SWITCHOVER_STATUS FROM V$DATABASE;

SWITCHOVER_STATUS 
----------------- 
TO_PRIMARY 
1 row selected

状态必须是TO PRIMARY 或 SESSIONS ACTIVE

2.6.切换备库角色为PRIMARY

SQL> ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY WITH SESSION SHUTDOWN;

2.7.打开数据库

SQL> ALTER DATABASE OPEN;