在同一事务中创建和使用表

时间:2015-11-30 14:01:28

标签: sql vba ms-access

我试图在ms访问中运行某个模块。这是我开始遇到问题的部分:

For i= asc("A") To asc("C") 
    DBEngine.Workspaces(0).BeginTrans
    '...a lot more code...
    strSql = "SELECT table.string, Count(*) INTO tableCount FROM table LEFT JOIN table2 ON table.string= table2.string WHERE table2.string Is Null AND (((table.string) Like [param])) GROUP BY table.string HAVING (((Count(*))>1))"
        DoCmd.SetWarnings False
        Set qdf = CurrentDb.CreateQueryDef("", strSql)
        qdf.Parameters("param").Value = Chr(i) & "*"
        Call qdf.Execute(dbFailOnError)
        DoCmd.SetWarnings True
        If DCount("*", "tableCount") = 0 Then 'check if there were records
            GoTo nextIteration
        End If
        '...a lot more code using tableCount if DCount shows that there are records...
    DBEngine.Workspaces(0).CommitTrans
Next i

到达DCount检查时出现错误:

Microsoft Access引擎找不到输入表或查询'tableCount'...

表格没有出现在数据库中。我尝试在Access中创建查询中运行strSql中的查询。当我被问到param时,我输入了A*,它运行正常。表tableCount不是在事务提交之前在数据库中创建的,但我在事务中需要它,而不仅仅是DCount。有没有办法在提交之前使用表或它的数据? 请在评论中询问您需要的任何其他信息以便回答我。我会马上回复。

1 个答案:

答案 0 :(得分:0)

使用以下内容更简单,并将所有内容保留在事务中:

Dim dbS As DAO.Database
Dim wsP As DAO.Workspace
Dim lngRecs as Long
Set wsP = DBEngine.Workspaces(0)
Set dbS = CurrentDb
strSql = "SELECT table.string, Count(*) INTO tableCount FROM table LEFT JOIN table2 ON table.string= table2.string WHERE table2.string Is Null AND (((table.string) Like '" & Chr(i) & "*'")) GROUP BY table.string HAVING (((Count(*))>1))"
wsP.BeginTrans
dbS.Execute strSql, dbFailOnError
lngRecs = dbS.RecordsAffected 
If Not lngRecs > 0 Then
   GoTo nextIteration 
End If
'Do whatever you like with lngRecs
wsP.CommitTrans dbForceOSFlush