問題:
如何設定表的某字段默認值?
方法一:
用 JET SQL 來完成
ALTER TABLE TABLENAME ALTER COLUMN FIELDNAME TEXT(40) DEFAULT 默認值
請注意,上述語句要用 ADODB.CONNECTION.EXECUTE 等方法來執行,直接用上述代碼建立一個查詢無法保存或者運行,會得到 Access 的錯誤提示。
方法二:
ADOX 可以。
Function ChengTableFIEldPro_ADO()
Dim MyTableName As String
Dim MyFIEldName As String
Dim GetFIEldDesc_ADO
Dim GetFIEldDescription
MyTableName = "ke_hu"
MyFIEldName = "dw_name"
Dim MyDB As New ADOX.Catalog
Dim MyTable As ADOX.Table
Dim MyFIEld As ADOX.Column
On Error GoTo Err_GetFIEldDescription
MyDB.ActiveConnection = CurrentProject.Connection
Set MyTable = MyDB.Tables(MyTableName)
GetFieldDesc_ADO = MyTable.Columns(MyFieldName).PropertIEs("Description")
Dim pro As ADODB.Property
For Each pro In MyTable.Columns(MyFieldName).PropertIEs
Debug.Print pro.Name & " : " & pro.Value & " ---- type : " & pro.Type
Next
With MyTable.Columns(MyFIEldName)
'.PropertIEs("nullable") = True '必填
'必填無法用上述代碼設置,出錯提示為:
'多步 OLE DB 操作產生錯誤。如果可能,請檢查每個 OLE DB 狀態值。沒有工作被完成。
'目前可以用以下語句設置:
'CurrentDb.TableDefs("ke_hu").Fields("DW_NAME").PropertIEs("Required") = False
.PropertIEs("Jet OLEDB:Allow Zero Length") = True '允許空
.PropertIEs("default") = "默默默默認認認認" '默認值
End With
Set MyDB = Nothing
Bye_GetFIEldDescription:
Exit Function
Err_GetFIEldDescription:
Beep
Debug.Print Err.Description
MsgBox Err.Description, vbExclamation
GetFIEldDescription = Null
Resume Bye_GetFIEldDescription
End Function
關於“多步錯誤”的一些參考::
Sub ChangeUnicode()
Dim tdf As TableDef
Dim fld As FIEld
Dim db As Database
Dim pro As Property
Set db = CurrentDb
For Each tdf In db.TableDefs
For Each fld In tdf.FIElds
If fld.Type = dbText Then
If DBEngine.Errors(0).Number = 3270 Then
Set pro = fld.CreateProperty("UnicodeCompression", 1, 0)
fld.PropertIEs.Append p
End If
fld.PropertIEs("UnicodeCompression") = True
End If
Next fld
Next tdf
End Sub