2013-07-11 52 views
0

我在Informix DB中有一张表,我想一次插入多条记录。 数据的列的一个应该是唯一的&其他列数据可能对所有我插入记录相同用于将多个记录插入数据库的Shell脚本

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

INSERT INTO员工(EMPID,国家,状态)值(1,us,ca)

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

我在寻找类似的循环EMPID &提示用户在用户进入起始值为1个&结束值100,脚本应该EMPID的1插页100个记录输入EMPID 值的开始&结束范围100

回答

0

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

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

我试过这个,但在执行脚本时,我在行start ='expr $ start + 1'处看到一个错误, – user2573747

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 

呼叫从外壳存储过程提示:

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);其中, SQL Server:INSERT INTO表VALUES(0),(1),(2); < - 3行

相关问题