☆☆ changechange 请进。一个简单问题请教: 用代码一次加入多行数据。

victorycyz 2004-04-03 11:09:46

在前台录入了一批记录,想一次提交。如果是SQL Server,可以这样写:

insert tablename (fieldname)
select 'a'
union select 'b'
union select 'c'
union ...

而Access好象不支持这种语法,那么在Access中怎么处理好呢?

谢谢回复。

...全文
47 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
victorycyz 2004-04-03
  • 打赏
  • 举报
回复

这样是多次执行了。没有更好的办法了吗?
changechange 2004-04-03
  • 打赏
  • 举报
回复
SQLSERVER 中存储过程是组织起来的多句SQL

ACCESS 中没有这种概念,但是可以用VBA来批量组织SQL语句。
比如
currentproject.connection.execute "insert tablename (fieldname) values('" & 变量 & "')"
currentproject.connection.execute "insert tablename (fieldname) values('" & 变量1 & "')"
currentproject.connection.execute "insert tablename (fieldname) values('" & 变量2 & "')"

即可
changechange 2004-04-03
  • 打赏
  • 举报
回复
当然测试过,可以运行的

temptable 存在么?拼写错误么?为什么不用 UNION ALL? 为什么后面还要用别名?
这些我的例子里面都没有的
victorycyz 2004-04-03
  • 打赏
  • 举报
回复

我直接在Access中写了一个这样的语句,可是它报语法错误呢?说“from子句语法错误”。

语句差不多是这样写的:

insert into tablename (fieldname)
select a
from
( select "a" as a from temptable
union
select "b" from temptable
union
...
) as t

你有没有测试过?
changechange 2004-04-03
  • 打赏
  • 举报
回复
呵呵,上述代码只是为了达到目的,我是不会在实际应用中这样写代码的。
changechange 2004-04-03
  • 打赏
  • 举报
回复
当然可以放在一行,但是 JET SQL 里面没有变量这个概念,所以要同时插入多行是很无聊的。


Function insertNRows()
'一次插入多行指定的值

'一下插入数字
Dim strSQL As String
Dim lngA(2) As Long
lngA(0) = 1
lngA(1) = 2
lngA(2) = 54

strSQL = "insert into 表1(字段2) select a from ("
strSQL = strSQL & "select max(0) + " & lngA(0) & " as a from 表2 union all "
strSQL = strSQL & "select max(0) + " & lngA(1) & " as a from 表2 union all "
strSQL = strSQL & "select max(0) + " & lngA(2) & " as a from 表2"
strSQL = strSQL & ")"

'注意,这里的表2 可以是什么记录都没有的空表,只是为了满足 FROM 子句
'如果表2只有一条记录,就可以把 MAX 去掉了。
Debug.Print strSQL
CurrentProject.Connection.Execute strSQL

'以下插入文字
Dim strA(2) As String
strA(0) = "my"
strA(1) = "u"
strA(2) = "i"

strSQL = "insert into 表1(字段5) select a from ("
strSQL = strSQL & "select max('') & '" & strA(0) & "' as a from 表2 union all "
strSQL = strSQL & "select max('') & '" & strA(1) & "' as a from 表2 union all "
strSQL = strSQL & "select max('') & '" & strA(2) & "' as a from 表2"
strSQL = strSQL & ")"

Debug.Print strSQL
CurrentProject.Connection.Execute strSQL

End Function

7,713

社区成员

发帖
与我相关
我的任务
社区描述
Microsoft Office Access是由微软发布的关系数据库管理系统。它结合了 MicrosoftJet Database Engine 和 图形用户界面两项特点。
社区管理员
  • Access
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧