#!/bin/bash # 设置数据库连接信息 DB_HOST="LOCALHOST" DB_PORT="1521" DB_SID="pdb" DB_USER="mics" DB_PASS="GZL11mics" TNS_SERVICE="${DB_SID}" START_TIME=$(date +"%Y-%m-%d %H:%M:%S") echo "开始时间: $START_TIME" # 定义物化视图的名称列表 MV_NAMES=("mv_entity_device_data" "mv_device_status" "mv_user_data") # 添加多个物化视图名称 # 循环处理每个物化视图 for MV_NAME in "${MV_NAMES[@]}"; do echo "正在检查物化视图: $MV_NAME" # 使用 here document 执行 SQL 查询,确保格式正确 RESULT=$(sqlplus -s "$DB_USER/$DB_PASS@//${DB_HOST}:${DB_PORT}/${TNS_SERVICE}" <<EOF SET HEADING OFF SET FEEDBACK OFF SET VERIFY OFF SET ECHO OFF SELECT COUNT(*) FROM all_mviews WHERE mview_name = UPPER('$MV_NAME'); EXIT; EOF ) # 去除空格、换行等不必要的字符 RESULT=$(echo "$RESULT" | tr -d '[:space:]') # 检查 RESULT 是否为有效的数字 if [[ "$RESULT" =~ ^[0-9]+$ ]]; then if [ "$RESULT" -gt 0 ]; then # 获取创建物化视图的SQL CREATE_MV_SQL=$(sqlplus -s "$DB_USER/$DB_PASS@//${DB_HOST}:${DB_PORT}/${TNS_SERVICE}" <<EOF SET HEADING OFF SET FEEDBACK OFF SET VERIFY OFF SET ECHO OFF SET LONG 10000 SET LONGCHUNKSIZE 10000 SELECT DBMS_METADATA.GET_DDL('MATERIALIZED_VIEW',UPPER('$MV_NAME'), 'MICS') FROM dual; EXIT; EOF ) # 去除多余的换行和空格 CREATE_MV_SQL=$(echo "$CREATE_MV_SQL" | tr -d '\n' | tr -s ' ') CREATE_MV_SQL="${CREATE_MV_SQL};" echo $CREATE_MV_SQL > create_mv_view.sql echo "commit;" >> create_mv_view.sql echo "exit;" >> create_mv_view.sql echo "物化视图 $MV_NAME 存在,正在删除旧的物化视图..." # 删除已有的物化视图 DELETE_MV_SQL="DROP MATERIALIZED VIEW $MV_NAME;" # 执行删除物化视图的 SQL echo "$DELETE_MV_SQL" | sqlplus -s "$DB_USER/$DB_PASS@//${DB_HOST}:${DB_PORT}/${TNS_SERVICE}" echo "物化视图 $MV_NAME 已删除,正在重新创建..." # 执行创建物化视图的 SQL sqlplus -s "$DB_USER/$DB_PASS@//${DB_HOST}:${DB_PORT}/${TNS_SERVICE}" @create_mv_view.sql > cr.log 2>&1 echo "物化视图 $MV_NAME 已重新创建。" else echo "物化视图 $MV_NAME 不存在,请先手动创建视图" fi else # 如果 RESULT 不是有效数字 echo "查询结果无效或为空,跳过物化视图 $MV_NAME" fi # 记录结束时间 END_TIME=$(date +"%Y-%m-%d %H:%M:%S") echo "结束时间: $END_TIME" done
标签:shell,NAME,DB,视图,物化,MV,Oracle,echo From: https://www.cnblogs.com/dll102/p/18609270