【问题标题】:Shell script for insert multiple records into a Database用于将多条记录插入数据库的 Shell 脚本
【发布时间】:2013-07-11 18:20:29
【问题描述】:

我在 Informix DB 中有一个表,我想一次向其中插入多条记录。 其中一列的数据应该是唯一的,而我插入的所有记录的其他列数据可能相同

我用来插入一行的典型插入语句:

插入员工(empid, country, state) 值(1, us, ca)

现在我想为“empid”列传递不同的值,其余列中的数据可以保持不变。

我正在寻找类似循环 empid 和提示用户输入 empid 值的开始和结束范围的东西 当用户输入起始值为 1 和结束值为 100 时,脚本应插入 100 条记录,其中 empid 的范围为 1 到 100

【问题讨论】:

    标签: shell unix informix


    【解决方案1】:

    请注意,您需要将开始和结束参数作为输入参数传递给脚本:

    #!/bin/sh
    
    start=$1
    end=$2
    
    while [[ $start -le $end ]];
    do
      echo "insert into employee(empid, country, state) values(${start}, us, ca)"
      start=`expr $start + 1`
    done
    

    【讨论】:

    • 我试过了,但是在执行脚本时,我在 start='expr $ start + 1' 这一行看到了一个错误
    【解决方案2】:

    此解决方案使用存储过程将插入语句包装在一个循环中。可能更适合性能至关重要的大量数据:

    文件 InsertEmployee.sql

    drop procedure InsertEmployee;
    
    create procedure InsertEmployee(
            p_start_empid   like employee.empid,
            p_end_empid     like employee.empid,
            p_country       like employee.country,
            p_state         like employee.state
    ) returning char(255);
    
            define i integer;
    
            let i = p_start_empid;
    
            while i <= p_end_empid
                    insert into employee (
                            empid,
                            country,
                            state
                    ) values (
                            i,
                            p_country,
                            p_state
                    );
    
                    -- logging
                    -- if (DBINFO('sqlca.sqlerrd2') > 0) then
                    --      return "inserted empid=" || i || " country=" || p_country || " state=" || p_state with resume;
                    -- end if
    
                    let i = i + 1;
            end while;
    end procedure;
    

    将存储过程加载到您的数据库中:

    dbaccess mydatabasename InsertEmployee.sql
    

    从 shell 提示符调用存储过程:

    echo 'execute procedure InsertEmployee(1,100,"us","ca");' | dbaccess mydatabasename
    

    【讨论】:

      【解决方案3】:
      #!/bin/bash
      
      declare -a namesArray=("name1","name2","name3")
      
      inserts=""
      
      for i in "{arr[@]}"
      do
          inserts+="INSERT INTO persons(id, name) VALUES (0,'$i');"
      done
      
      echo $inserts | dbaccess yourDataBase
      

      这将插入 3 行(我假设您的主键是序列号,这就是为什么值字段中的 0)。在 informix 中,您不能在同一个插入中添加多行,这就是我为每行创建一个插入的原因。

      Informix:INSERT INTO 表 VALUES(0); mySQL & SQL Server: INSERT INTO table VALUES(0),(1),(2);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-21
        • 1970-01-01
        • 1970-01-01
        • 2018-05-07
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多