用sql设置access的默认值
简述:
如何定义字段默认值
问题:
如何设定表的某字段默认值?
方法一:
用 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