设为首页收藏本站Access中国

Office中国论坛/Access中国论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

用一个JET SQL 语句一次插入多行值到指定表中(“值”来自变量)

1970-1-1 08:00| 发布者: cg1| 查看: 2544| 评论: 0

原文:http://access911.net/71FAB21E12DCECF3.htm

问题:

  在前台录入了一批记录,想一次提交。如果是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 

最新评论

QQ|站长邮箱|小黑屋|手机版|Office中国/Access中国 ( 粤ICP备10043721号-1 )  

GMT+8, 2024-4-29 04:09 , Processed in 0.099568 second(s), 16 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

返回顶部