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?

【AccessVBA】一括更新のSQL文

Last updated at Posted at 2025-06-05

ポイント

  • 一括INSERT文
  • 一括UPDATE文
  • トランザクション

一括INSERT文 & トランザクション

Public Function func_aaa() As Boolean
    Dim conn As ADODB.Connection
    Dim strSQL As String
    On Error GoTo ErrorExit  

    func_aaa = False
    
    Set conn = CurrentProject.Connection

    '有効フラグ=Falseになったデータを、履歴テーブルにINSERTして、元テーブルからは削除する処理
    'トランザクション処理によりデータの整合性を保持する

    ' トランザクション開始
    conn.BeginTrans
    
    ' INSERT文
    strSQL = ""
    strSQL = strSQL & "INSERT INTO 顧客マスタ_履歴" & vbCrLf
    strSQL = strSQL & "    (顧客ID, 顧客名, 役職名)" & vbCrLf
    strSQL = strSQL & "SELECT" & vbCrLf
    strSQL = strSQL & "    顧客マスタ.顧客ID" & vbCrLf
    strSQL = strSQL & "    , 顧客マスタ.顧客名" & vbCrLf
    strSQL = strSQL & "    , 役職マスタ.役職名" & vbCrLf
    strSQL = strSQL & "FROM 顧客マスタ" & vbCrLf
    strSQL = strSQL & "LEFT JOIN 役職マスタ ON 顧客マスタ.役職ID = 役職マスタ.役職ID" & vbCrLf 
    strSQL = strSQL & "WHERE 顧客マスタ.有効フラグ = False" & vbCrLf
    conn.Execute strSQL
    
    ' DELETE文
    strSQL = ""
    strSQL = strSQL & "DELETE * FROM 顧客マスタ" & vbCrLf
    strSQL = strSQL & "WHERE 有効フラグ = False" & vbCrLf
    conn.Execute strSQL

    ' 成功したらコミット
    conn.CommitTrans

    func_aaa = True
    
    GoTo EndExit

ErrorExit:
    'エラーのためロールバック
    conn.RollbackTrans
    MsgBox "エラーが発生しました:" & Err.Description, vbCritical
    
EndExit:
    On Error Resume Next
    Exit Function
    
End Function

一括UPDATE文

Public Function func_aaa() As Boolean
    Dim conn As ADODB.Connection
    Dim strSQL As String
    On Error GoTo ErrorExit  

    func_aaa = False
    
    Set conn = CurrentProject.Connection
    
    ' UPDATE文
    strSQL = ""
    strSQL = strSQL & "UPDATE 顧客マスタ AS UPD" & vbCrLf
    strSQL = strSQL & "INNER JOIN 役職マスタ AS REF ON UPD.役職ID = REF.役職ID" & vbCrLf    
    strSQL = strSQL & "SET UPD.役職名 = REF.役職名" & vbCrLf
    strSQL = strSQL & "WHERE UPD.有効フラグ = True" & vbCrLf
    conn.Execute strSQL

    func_aaa = True
    
    GoTo EndExit

ErrorExit:
    MsgBox "エラーが発生しました:" & Err.Description, vbCritical
    
EndExit:
    On Error Resume Next
    Exit Function
    
End Function

補足

一括INSERT文
一括UPDATE文

  • 一括INSERT文は3つ以上のテーブルを参照して更新可能
  • 一括UPDATE文は2つのテーブルまでしか参照できない
    ※ループ処理などの対応が必要となる
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?