Sub TrySample_3_4()
Dim dbs As Database
Dim tdf As TableDef
Dim idx As Index
Dim fld As Field
Dim strSQL As String
Dim strDefVal As String
Set dbs = CurrentDb
For Each tdf In dbs.TableDefs
With tdf
If .Attributes = 0 And .Name <> "tblテーブル構造" Then
'Indexesコレクションのループ
For Each idx In tdf.Indexes
If idx.Primary Then
'主キーのとき
strSQL = "ALTER TABLE " & .Name & " ADD PRIMARY KEY " & _
"(" & idx.Fields(0).Name & ")"
ElseIf idx.Unique Then
'固有インデックスのとき
strSQL = "CREATE UNIQUE INDEX " & idx.Name & " ON " & .Name & _
" (" & idx.Fields(0).Name & ")"
Else
'固有でないインデックスのとき
strSQL = "CREATE INDEX " & idx.Name & " ON " & .Name & _
" (" & idx.Fields(0).Name & ")"
End If
'SQL文を発行
ExecSQL strSQL
Next idx
'Fieldsコレクションのループ
For Each fld In .Fields
strDefVal = fld.DefaultValue
If Len(strDefVal) > 0 Then
'既定値があるとき
If strDefVal = "Yes" Then
strDefVal = "1"
ElseIf strDefVal = "No" Then
strDefVal = "0"
ElseIf strDefVal = "=Date()" Then
strDefVal = "CONVERT(date, GETDATE())"
End If
strSQL = "ALTER TABLE " & .Name & " ADD DEFAULT " & strDefVal & _
" FOR " & fld.Name
'SQL文を発行
ExecSQL strSQL
End If
Next fld
End If
End With
Next tdf
End Sub
Private Sub ExecSQL(strSQL As String)
'SQL Server上にSQL文を発行する
Dim dbs As Database
Dim strConStr As String
strConStr = "ODBC;DRIVER=SQL Server;" & _
"SERVER=NAFUREI;" & _
"DATABASE=UpSizeTest;" & _
"Trusted_Connection=Yes;"
On Error GoTo Err_Handler
'SQL Server上のUpSizeTestデータベースに接続
Set dbs = OpenDatabase("", False, False, strConStr)
'SQL文をSQL Serverに発行
dbs.Execute strSQL, dbSQLPassThrough
Exit_Here:
Exit Sub
Err_Handler:
MsgBox "エラー番号:" & Err.Number & vbCrLf & vbCrLf & _
"エラー内容:" & Err.Description, vbOKOnly + vbCritical
Resume Exit_Here:
End Sub