Michael J. Strickland said:
I have several tables with Primary key fields containing nulls so I think
you are wrong
I know if you try to designate a field containing Nulls as a Priamry Key
in the Table Design
window it objects, yet you are allowed to do so in code.
If what you say is true, then these 2 statements should generate a
compiler error ( or at least a runtime error), yet they do not:
indIndex.Primary = True
indIndex.Required = False
My tests indicate that if you execute the two lines in this order ...
idx.Primary = True
idx.Required = False
.... you get an index that is not Primary and allows Null. If, on the other
hand, you execute the same two lines in the opposite order ...
' idx.Required = False
' idx.Primary = True
.... you get an index that is Primary and does not allow Null.
It would appear that the second instruction silently over-rides the first.
Here's my test code. Run it once as is, then swap the commented lines and
run it again.
Public Sub TestPKNull()
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Dim idx As DAO.Index
Set db = CurrentDb
On Error Resume Next
db.TableDefs.Delete ("MyTestTable")
On Error GoTo 0
Set tdf = db.CreateTableDef("MyTestTable")
Set fld = tdf.CreateField("TestText", dbText, 50)
fld.Required = False
tdf.Fields.Append fld
Set fld = tdf.CreateField("TestLong", dbLong)
tdf.Fields.Append fld
db.TableDefs.Append tdf
Set idx = tdf.CreateIndex("MyPK")
Set fld = idx.CreateField("TestText", dbText, 50)
idx.Fields.Append fld
'Results in index that is not Primary and allows Null
'Comment out these lines on second run.
idx.Primary = True
idx.Required = False
' 'Results in index that is Primary and does not allow Null
' 'Uncomment these lines on second run.
' idx.Required = False
' idx.Primary = True
tdf.Indexes.Append idx
Debug.Print idx.Primary
Debug.Print idx.Required
'This will raise an error on the second run.
CurrentDb.Execute "INSERT INTO MyTestTable (TestText, TestLong) VALUES
(NULL, 1)", dbFailOnError
End Sub