用于将多个记录插入数据库的Shell脚本

问题描述 投票:0回答:3

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

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

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

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

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

shell unix informix
3个回答
0
投票

请注意,您需要将start和end参数作为输入参数传递给脚本:

#!/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

0
投票

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

文件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

0
投票
#!/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表VALUES(0),(1),(2); < - 3行

© www.soinside.com 2019 - 2024. All rights reserved.