簡述:
如何定義字段默認值
問題:
如何設定表的某字段默認值?
方法一:
用 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