我有一个包含数百个查询的 access 2003 数据库文件。我想根据条件重命名查询中引用的所有表
If tableNameInQuery = "tableName" Then
tableNameInQuery = "newTableName"
End If
附上 C# 或 VB.NET 中的示例将不胜感激
最佳答案
我有一个快速而肮脏的 VBA 子程序,它可以执行我认为您想要的操作。 (你能把它翻译成你喜欢的语言之一吗?)你可以用你的数据库的副本来试试。 (不要尝试使用您想要保留的数据库的唯一副本!)
要在您的查询中用 "tblBar" 替换 "tblFoo",您可以从 VBE 即时窗口运行它(从 Access,Ctrl+g 会带你到那里)像这样:
call swapTblNamesInQueryDefs("tblFoo", "tblBar")
要实际保存更改的查询定义,请这样调用它:
call swapTblNamesInQueryDefs("tblFoo", "tblBar", "savechanges")
代码:
Public Sub swapTblNamesInQueryDefs(ByVal pstrFind As String, _
ByVal pstrReplace As String, _
Optional ByVal pstrMode As String = "DisplayOnly")
Dim qd As QueryDef
Dim re As Object
Dim strSql As String
Set re = CreateObject("vbscript.regexp")
re.Global = True
re.IgnoreCase = True
re.Pattern = "\b" & pstrFind & "\b"
For Each qd In CurrentDb.QueryDefs
If Left$(qd.Name, 1) <> "~" Then
Debug.Print qd.Name
Debug.Print "Before: " & qd.SQL
strSql = re.Replace(qd.SQL, pstrReplace)
Debug.Print "After: " & strSql
'only save the modified SQL statement if called
'with SaveChanges parameter
'If pstrMode = "SaveChanges" Then
If StrComp(pstrMode, "SaveChanges", vbTextCompare) = 0 Then
qd.SQL = strSql
End If
Debug.Print String(20, "-")
End If
Next qd
Set re = Nothing
Set qd = Nothing
End Sub
编辑:更改了 pstrMode
的评估以保证不区分大小写的比较(如果模块包含“Option Compare Binary”)。
关于c# - 以编程方式重命名 Access 查询中的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1222475/