0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

vbaからsql文を作成する

Posted at
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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?