我觉得还是定义两个数据库连接 '定义recordset,connection并打开 dim strSqlSelect as string dim strSqlInsert as string strSqlSelect="SELECT * FROM A" rsSelect.open strSqlSelect,cnSelect,1,3 dim i as integer dim iCount as integer iCount =rsSelect.recordcount for i=1 to iCount strSqlInsert="INSERT INTO B (...) VALUES (" & rsSelect("f1Name") & ... & ") on error resume next cnInsert.execute strSqlInsert if err.number<>0 then msgbox err.description'如果可能在后面加上回滚操作 RollBack endif rsSelect.movenext next Dim conn As New ADODB.Connection Dim cors As New ADODB.Recordset Dim strsql As String conn.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;" _ & "Data Source=" & App.Path & "\****.mdb;Jet OLEDB:database ") strsql="select * from table where 条件" cors.open strsql,conn,3,1 do while not cors.eof conn.execute("insert into table(**,**,...,**) value('" & cors("**") & "',...)") cors.movenext loop cors.close set cors=nothing conn.close set conn=nothing 如果仅在同一个数据库中操作,将数据从一个数据库的插入到另一个表中 以mysql数据库为例分情况一一说明: 两张表:insertTest和insertTest2,前者中有测试数据 create table insertTest(id int(4),name varchar(12)); insert into insertTest values(100,'liudehua'); insert into insertTest values(101,'zhourunfa'); insert into insertTest values(102,'zhouhuajian');
1.如果2张表的字段一致,并且希望插入全部数据,可以用这种方法: INSERT INTO 目标表 SELECT * FROM 来源表; insert into insertTest select * from insertTest2;
2.如果只希望导入指定字段,可以用这种方法: INSERT INTO 目标表 (字段1, 字段2, ...) SELECT 字段1, 字段2, ... FROM 来源表; 注意字段的顺序必须一致。 insert into insertTest2(id) select id from insertTest2;
3.如果您需要只导入目标表中不存在的记录,可以使用这种方法: INSERT INTO 目标表 (字段1, 字段2, ...) SELECT 字段1, 字段2, ... FROM 来源表 WHERE not exists (select * from 目标表 where 目标表.比较字段 = 来源表.比较字段); 1>.插入多条记录: insert into insertTest2 (id,name) select id,name from insertTest where not exists (select * from insertTest2 where insertTest2.id=insertTest.id); 2>.插入一条记录: insert into insertTest (id, name) SELECT 100, 'liudehua' FROM dual WHERE not exists (select * from insertTest where insertTest.id = 100); 使用 dual 作表名,select 语句后面直接跟上要插入的字段的值。 4.将查询出来的数据并同其他变量一起插入新的数据表中 insert into t_supp_PurchPlan_s(PurPlanCode,itemcode,Speccode) select 'hello'as PurPlanCode,itemcode,speccode from b_item where id=8
直接将变量放到相应的位置即可(如上将固定的变量或动态变量放入即可)
|
Dim conn As New ADODB.Connection
Dim conn2 As New ADODB.Connection
Dim cors As New ADODB.Recordset
Dim strsql As String
'第一个连接
conn.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;" _
& "Data Source=" & App.Path & "\****.mdb;Jet OLEDB:database ")
'第二个连接
conn2.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;" _
& "Data Source=" & App.Path & "\****.mdb;Jet OLEDB:database ")
strsql="select * from table where 条件"
cors.open strsql,conn,3,1
do while not cors.eof
conn2.execute("insert into table(**,**,...,**) value('" & cors("**") & "',...)")
cors.movenext
loop
cors.close
set cors=nothing
conn.close
set conn=nothing
conn2.close
set conn2=nothing