java之生成可重復執行的sql腳本


  在實際項目開發過程中,sql腳本需要多次執行。而一般的DML和DDL語句一般只能執行一次,再次執行執行時就會報錯(操作對應已存在/不存在),所以必須將sql腳本生成可重復執行的。本文共分為4部分:1.什么是DDL和DML;2.DDL可重復執行腳本;3.DML可重復執行腳本。

1.什么是DDL和DML

  DDL: Data Defination Language,即數據定義語言。主要是是對表進行操作(DROP, CREATE,ALTER...)

  DML: Data Management Language,即數據控制語句。主要是對記錄進行操作(INSERT,DELETE,UPDATE....)

 

2.DDL可重復執行腳本

  2.1 通用格式:

-- 定義便變量並賦值
DECLARE
    varName SqlType := value;
     V_SQL VARCHAR2(1000) := SqlStatement;
-- 執行邏輯
BEGIN
    IF IfCondition THEN
       EXECUTE IMMEDIATE V_SQL;
    END IF;
END;
-- ‘/’可看作結束符
/

  2.2  創建一張新的表單以及序列

DECLARE
    V_TABLE VARCHAR2(100):='T_DEFINE';
    V_CREATE_SQL VARCHAR2(2000):='CREATE TABLE T_GRI_TREATY_DEFINE(
                                  ID NUMBER(10) PRIMARY KEY,
                                  TREATY_ID NUMBER(10) not null,
                                  RISK_CAT NUMBER(10) not null,
                                  ANNUAL_AGG_LIMIT_FLAG NUMBER(1) DEFAULT 2,
                                  ANNUAL_AGG_LIMIT_AMOUNT NUMBER(24,4),
                                  INSERT_BY NUMBER(10),
                                  INSERT_TIME DATE,
                                  UPDATE_BY NUMBER(10),
                                  UPDATE_TIME DATE
                            )';
    V_SEQUENCE_SQL VARCHAR2(2000):='CREATE SEQUENCE S_GRI_TREATY_DEFINE_ID';
    V_CNT NUMBER:=0;
BEGIN
  -- 查詢表是否存在(0:不存在,1:存在) SELECT COUNT(1) INTO V_CNT FROM USER_TAB_COLUMNS T WHERE T.TABLE_NAME=V_TABLE; IF V_CNT=0 THEN EXECUTE IMMEDIATE V_CREATE_SQL; EXECUTE IMMEDIATE V_SEQUENCE_SQL; END IF; END; /

  2.2 給表中的列添加注釋

DECLARE
    V_COLUMN VARCHAR2(100):='ID';
    V_TABLE VARCHAR2(100):='T_DEFINE';
-- 注釋的內容必須用兩個單引號括起來 V_SQL
VARCHAR2(2000):='COMMENT ON COLUMN T_DEFINE.ID IS ''PK S_DEFINE_ID'''; V_CNT NUMBER:=0; BEGIN
  -- 查詢列是否存在 SELECT COUNT(1) INTO V_CNT FROM USER_TAB_COLUMNS T WHERE T.TABLE_NAME=V_TABLE AND T.COLUMN_NAME=V_COLUMN ; IF V_CNT>0 THEN EXECUTE IMMEDIATE V_SQL; END IF; END; /

  2.3 給表添加一列(alter其他語句例子基本相同,只需要修改V_SQL的值和IF的條件)

DECLARE
    V_COLUMN VARCHAR2(100):='LIMIT_AMOUNT';
    V_TABLE VARCHAR2(100):='T_TREATY';
    V_SQL VARCHAR2(2000):='ALTER TABLE T_TREATY ADD LIMIT_AMOUNT NUMBER(24,4) ';
    V_CNT NUMBER:=0;
BEGIN
    SELECT COUNT(1) INTO V_CNT FROM USER_TAB_COLUMNS T WHERE T.TABLE_NAME=V_TABLE AND T.COLUMN_NAME=V_COLUMN ;
    IF V_CNT=0 THEN
       EXECUTE IMMEDIATE V_SQL;
    END IF;
END;
/

 

3. DML可重復執行腳本

  3.1 update語句本身就可以多次執行,因此不用進行特殊處理

  3.2 insert語句只需要在insert之前追加delete語句即可。

delete from t_vehicle_info where VEHICLE_ID = 1763154645;

insert into t_th_int_redbook_info (VEHICLE_ID,MAKE_NAME, FAMILY_NAME, DESCRIPTION, UPDATE_TIME)
values (1763154645, 'BMW', '430i', 'BMW 430i Coupe M Sport', '11-JUL-17');

 

4. 用Java生成DDL可重復執行腳本

package com.ebao.th.gs.integration.util;

import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GeneraterPKGUtils {

  public static final String FILE_SPLIT="_";
    
  public static void main(String[] args) {
       
    //調用函數
       
    //生成文件
    
  }
  
  public static String generaterModifyColType(String column,String tableName,String type){
    StringBuffer pkg = new StringBuffer();
    pkg.append("declare\r\n");
    pkg.append("    v_column varchar2(100):='"+column+"';\r\n");
    pkg.append("    v_table varchar2(100):='"+tableName+"';\r\n");
    pkg.append("    v_sql varchar2(2000):='ALTER TABLE "+tableName+" MODIFY "+column+type+"';\r\n");
    pkg.append("    v_cnt number:=0;\r\n");
    pkg.append("begin\r\n");
    pkg.append("    select count(1) into v_cnt from user_tab_columns t where t.TABLE_NAME=v_table and t.COLUMN_NAME=v_column;\r\n");
    pkg.append("    if v_cnt>0 then\r\n");
    pkg.append("       execute immediate v_sql;\r\n");
    pkg.append("    end if;\r\n");
    pkg.append("end;\r\n");
    pkg.append("/\r\n");
    return pkg.toString().toUpperCase();
  }
  
  
  public static String generaterRenameColumn(String column,String tableName){
    StringBuffer pkg = new StringBuffer();
    pkg.append("declare\r\n");
    pkg.append("    v_column varchar2(100):='"+column+"';\r\n");
    pkg.append("    v_table varchar2(100):='"+tableName+"';\r\n");
    pkg.append("    v_sql varchar2(2000):='alter table "+tableName.toUpperCase()+" rename column "+column+" to "+column.replaceAll("Insured", "Holder").toUpperCase()+"';\r\n");
    pkg.append("    v_cnt number:=0;\r\n");
    pkg.append("begin\r\n");
    pkg.append("    select count(1) into v_cnt from user_tab_columns t where t.TABLE_NAME=v_table and t.COLUMN_NAME=v_column ;\r\n");
    pkg.append("    if v_cnt>0 then\r\n");
    pkg.append("       execute immediate v_sql;\r\n");
    pkg.append("    end if;\r\n");
    pkg.append("end;\r\n");
    pkg.append("/\r\n");
    return pkg.toString().toUpperCase();
  }
  
  public static String generateCreateTable(String tableStr,String tableName){
    StringBuffer pkg = new StringBuffer();
    pkg.append("declare\r\n");
    pkg.append("    v_table varchar2(100):='"+tableName+"';\r\n");
    pkg.append("    v_sql varchar2(2000):='"+tableStr.trim()+"';\r\n");
    pkg.append("    v_cnt number:=0;\r\n");
    pkg.append("begin\r\n");
    pkg.append("    select count(1) into v_cnt from user_tables t where t.TABLE_NAME=v_table ;\r\n");
    pkg.append("    if v_cnt=0 then\r\n");
    pkg.append("       execute immediate v_sql;\r\n");
    pkg.append("    end if;\r\n");
    pkg.append("end;\r\n");
    pkg.append("/\r\n");
    return pkg.toString().toUpperCase();
  }
  
  public static String renameColumn(String column,String tableName,String type){
    StringBuffer pkg = new StringBuffer();
    pkg.append("declare\r\n");
    pkg.append("    v_column varchar2(100):='"+column.trim()+"';\r\n");
    pkg.append("    v_table varchar2(100):='"+tableName.trim()+"';\r\n");
    pkg.append("    v_sql varchar2(2000):='ALTER TABLE "+tableName+" rename column "+column+" to "+type+"';\r\n");
    pkg.append("    v_cnt number:=0;\r\n");
    pkg.append("begin\r\n");
    pkg.append("    select count(1) into v_cnt from user_tab_columns t where t.TABLE_NAME=v_table and t.COLUMN_NAME=v_column  ;\r\n");
    pkg.append("    if v_cnt>0 then\r\n");
    pkg.append("       execute immediate v_sql;\r\n");
    pkg.append("    end if;\r\n");
    pkg.append("end;\r\n");
    pkg.append("/\r\n");
    return pkg.toString().toUpperCase();
  }
  
   public static String generatePrimaryKey(String column,String tableName,String type,String constraintName){
     StringBuffer pkg = new StringBuffer();
     pkg.append("declare\r\n");
     pkg.append("    v_column varchar2(100):='"+column.toUpperCase()+"';\r\n");
     pkg.append("    v_table varchar2(100):='"+tableName.toUpperCase()+"';\r\n");
     pkg.append("    v_sql varchar2(2000):='alter table "+tableName.toUpperCase()+" add constraint "+constraintName.toUpperCase()+" primary key ("+column.toUpperCase()+") ';\r\n");
     pkg.append("    v_cnt number:=0;\r\n");
     pkg.append("begin\r\n");
     pkg.append("    select count(1) into v_cnt from user_constraints t where t.CONSTRAINT_NAME='"+constraintName.toUpperCase()+"' and constraint_type='"+type.toUpperCase()+"' and table_name=v_table ;\r\n");
     pkg.append("    if v_cnt=0 then\r\n");
     pkg.append("       execute immediate v_sql;\r\n");
     pkg.append("    end if;\r\n");
     pkg.append("end;\r\n");
     pkg.append("/\r\n");
     return pkg.toString().toUpperCase();
   }
  
  public static String createIndex(String column,String tableName,String type,String indexName){
    StringBuffer pkg = new StringBuffer();
    pkg.append("declare\r\n");
    pkg.append("    v_column varchar2(100):='"+column.toUpperCase()+"';\r\n");
    pkg.append("    v_table varchar2(100):='"+tableName.toUpperCase()+"';\r\n");
    pkg.append("    v_sql varchar2(2000):='create index "+indexName.toUpperCase()+" on "+tableName.toUpperCase()+"("+column.toUpperCase()+")';\r\n");
    pkg.append("    v_cnt number:=0;\r\n");
    pkg.append("begin\r\n");
    pkg.append("    select count(1) into v_cnt from user_indexes t where t.INDEX_NAME='"+indexName.toUpperCase()+"' and index_type='"+type.toUpperCase()+"' and table_name=v_table ;\r\n");
    pkg.append("    if v_cnt=0 then\r\n");
    pkg.append("       execute immediate v_sql;\r\n");
    pkg.append("    end if;\r\n");
    pkg.append("end;\r\n");
    pkg.append("/\r\n");
    return pkg.toString().toUpperCase();
  }
  

  public static String dropColumn(String column,String tableName){
    StringBuffer pkg = new StringBuffer();
    pkg.append("declare\r\n");
    pkg.append("    v_column varchar2(100):='"+column+"';\r\n");
    pkg.append("    v_table varchar2(100):='"+tableName+"';\r\n");
    pkg.append("    v_sql varchar2(2000):='alter table "+tableName+" drop column "+column+"';\r\n");
    pkg.append("    v_cnt number:=0;\r\n");
    pkg.append("begin\r\n");
    pkg.append("    select count(1) into v_cnt from user_tab_columns t where t.TABLE_NAME=v_table and t.COLUMN_NAME=v_column ;\r\n");
    pkg.append("    if v_cnt>0 then\r\n");
    pkg.append("       execute immediate v_sql;\r\n");
    pkg.append("    end if;\r\n");
    pkg.append("end;\r\n");
    pkg.append("/\r\n");
    return pkg.toString().toUpperCase();
  }
  
  public static String addComment(String column,String tableName,String comments){
    StringBuffer pkg = new StringBuffer();
    pkg.append("declare\r\n");
    pkg.append("    v_column varchar2(100):='"+column+"';\r\n");
    pkg.append("    v_table varchar2(100):='"+tableName.toUpperCase()+"';\r\n");
    pkg.append("    v_sql varchar2(2000):='COMMENT ON COLUMN "+tableName+"."+column+" IS ''"+comments+"'''\r\n;");
    pkg.append("    v_cnt number:=0;\r\n");
    pkg.append("begin\r\n");
    pkg.append("    select count(1) into v_cnt from user_tab_columns t where t.TABLE_NAME=v_table and t.COLUMN_NAME=v_column ;\r\n");
    pkg.append("    if v_cnt>0 then\r\n");
    pkg.append("       execute immediate v_sql;\r\n");
    pkg.append("    end if;\r\n");
    pkg.append("end;\r\n");
    pkg.append("/\r\n");
    return pkg.toString().toUpperCase();
  } 
  
  public static String addCommentOnTable(String tableName,String comments){
    StringBuffer pkg = new StringBuffer();
    pkg.append("declare\r\n");
    pkg.append("    v_table varchar2(100):='"+tableName.toUpperCase()+"';\r\n");
    pkg.append("    v_sql varchar2(2000):='comment on table "+tableName.toUpperCase()+" IS ''"+comments+"'''");
    pkg.append("    v_cnt number:=0;\r\n");
    pkg.append("begin\r\n");
    pkg.append("    select count(1) into v_cnt from user_tab_columns t where t.TABLE_NAME=v_table ;\r\n");
    pkg.append("    if v_cnt>0 then\r\n");
    pkg.append("       execute immediate v_sql;\r\n");
    pkg.append("    end if;\r\n");
    pkg.append("end;\r\n");
    pkg.append("/\r\n");
    return pkg.toString().toUpperCase();
  } 
  
  public static void generateFile(String sql,String name) throws Exception{
    String path="D:"+File.separator+"dbscript"+File.separator;
    File f = new File(path);
    if(!f.exists()){
      f.mkdirs();
    }
    FileWriter writer=null;
    String dateStr ="";
    SimpleDateFormat sim = new SimpleDateFormat("yyyyMMddHHmmss");
    dateStr = sim.format(new Date());
    String fileName = path+dateStr+FILE_SPLIT+name.trim().toUpperCase()+"_ddl.sql";
    try {
      writer = new FileWriter(fileName);
      writer.write(sql);
      writer.flush();
      Runtime.getRuntime().exec("notepad.exe "+fileName);
    }
    catch (Exception e) {
      //e.printStackTrace();
    }finally{
      writer.flush();
      if(writer!=null){
        writer.close();
      }
    }
    
  }
}

 

  更多內容,請訪問:http://www.cnblogs.com/BlueStarWei


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM