【发布时间】:2008-10-26 20:09:25
【问题描述】:
我是 Access 新手。我有一张满是记录的桌子。我想编写一个函数来检查任何 id 是否为空或空。如果是这样,我想用 xxxxx 更新它。 id 的检查必须在数据库中的所有表中运行。 谁能提供一些示例代码?
【问题讨论】:
我是 Access 新手。我有一张满是记录的桌子。我想编写一个函数来检查任何 id 是否为空或空。如果是这样,我想用 xxxxx 更新它。 id 的检查必须在数据库中的所有表中运行。 谁能提供一些示例代码?
【问题讨论】:
我不确定您是否能够使用 Access SQL 找到数据库中的所有表。相反,您可能想要编写一些 VBA 来遍历表并为每个表生成一些 SQL。大致如下:
update TABLE set FIELD = 'xxxxxx' where ID is null
【讨论】:
查看 Nz() 函数。当它用您指定的任何内容替换它们时,除非它们为空,否则它将保持字段不变。
对于合理数量和大小的表格,只需
找出空值的来源并阻止它们是一种很好的做法 - 为字段提供默认值,在输入上使用 Nz()。并让您的代码处理任何漏网的空值。
【讨论】:
我称它为 UpdateFieldWhereNull 函数,显示的是一个调用它的子例程(改编自 http://www.aislebyaisle.com/access/vba_backend_code.htm)
它会更新 DbPath 参数中的所有表(未测试,小心处理):
Function UpdateFieldWhereNull(DbPath As String, fieldName as String, newFieldValue as String) As Boolean
'This links to all the tables that reside in DbPath,
' whether or not they already reside in this database.
'This works when linking to an Access .mdb file, not to ODBC.
'This keeps the same table name on the front end as on the back end.
Dim rs As Recordset
On Error Resume Next
'get tables in back end database
Set rs = CurrentDb.OpenRecordset("SELECT Name " & _
"FROM MSysObjects IN '" & DbPath & "' " & _
"WHERE Type=1 AND Flags=0")
If Err <> 0 Then Exit Function
'update field in tables
While Not rs.EOF
If DbPath <> Nz(DLookup("Database", "MSysObjects", "Name='" & rs!Name & "' And Type=6")) Then
'UPDATE the field with new value if null
DoCmd.RunSQL "UPDATE " & acTable & " SET [" & fieldName & "] = '" & newFieldValue & "' WHERE [" & fieldName & "] IS NULL"
End If
rs.MoveNext
Wend
rs.Close
UpdateFieldWhereNull = True
End Function
Sub CallUpdateFieldWhereNull()
Dim Result As Boolean
'Sample call:
Result = UpdateFieldWhereNull("C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb", "ID", "xxxxxx")
Debug.Print Result
End Sub
【讨论】: