用一个JET SQL 语句一次插入多行值到指定表中(“值”来自变量)
2005-02-04 17:43:00
问题:
|
在前台录入了一批记录,想一次提交。如果是SQL Server,可以这样写:
insert tablename (fieldname)
select 'a'
union select 'b'
union select 'c'
union ...
而Access好象不支持这种语法,那么在access中怎么处理好呢?
|
回答:
|
当然可以放在一行,但是 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
|
呵呵,上述代码只是为了达到目的,我是不会在实际应用中这样写代码的。
很多人在看这篇文章的时候不得要领
1、表2必须有大于1条的记录数
2、UNION ALL 所连接的是表,绝对不能把 FROM 子句省略,这里不是 T-SQL 这里是 JET SQL
|