Sub GenerateCreateTableSQL()
Dim ws As Worksheet
Dim lastRow As Long
Dim tableName As String
Dim sql As String
Dim i As Long
Dim colName As String, colType As String
Dim isPrimaryKey As Boolean, isAutoIncrement As Boolean
' 対象のシートを設定
Set ws = ThisWorkbook.Sheets("USER")
' 物理テーブル名を取得
tableName = ws.Cells(4, 11).Value
' SQL文の初期化
sql = "CREATE TABLE スキーマ名." & tableName & " (" & vbCrLf
' 最後の行を取得(空白行を考慮)
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).row
' 8行目以降のカラム定義を読み込む
For i = 8 To lastRow
colName = ws.Cells(i, 10).Value ' 物理カラム名
colType = ws.Cells(i, 17).Value ' データ型
If Not ws.Cells(i, 22).Value = "-" Then
byteNum = "(" & ws.Cells(i, 22).Value & ")" 'バイト数
Else
byteNum = ""
End If
isPrimaryKey = (ws.Cells(i, 32).Value = "Yes") ' PKフラグ
isAutoIncrement = (ws.Cells(i, 37).Value = "AUTOINCREMENT") ' AUTO_INCREMENTフラグ
' カラム定義をSQL文に追加
sql = sql & " " & colName & " " & colType & byteNum
' 主キーなら追加
If isPrimaryKey Then
sql = sql & " PRIMARY KEY"
End If
' AUTO_INCREMENTがある場合は追加
If isAutoIncrement Then
sql = sql & " AUTO_INCREMENT"
End If
sql = sql & "," & vbCrLf
Next i
' 最後のカンマを削除してSQLを閉じる
sql = Left(sql, Len(sql) - 3) & vbCrLf & ");"
' SQL文をメッセージボックスで表示
MsgBox sql
End Sub
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme