2
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?

More than 5 years have passed since last update.

InsertされたレコードをSelectする

2
Last updated at Posted at 2020-08-13

主キーにauto_incrementが指定してあるテーブルに
insertした後、そのinsertした行のauto_incrementがされている値が欲しい場合、
Insertした直後にすぐにselect文でmax()や@@identifyを使って持ってくる方法がありますが、

複数からの同時実行などを考慮すると少し不安なものがありますよね、、、

色々試行錯誤して、ある記事
を参考にしてその解決方法を見つけました。

**「Insert文にて"OUTPUT句"を使い、挿入した行の特定の値を抽出する」**方法です。

id(Primary/auto_increment) name remarks
1 test1-1 test1-2
2 test2-1 test2-2
3 test3-1 test3-2

※ transactionによる処理(複数人からの同時実行考慮/主キーautoincrement時)

Private Function insertAndSelect() As Integer
    Dim conn As SqlConnection
    Dim cmd As New SqlCommand
    Dim tran As SqlTransaction
    DIm result As Integer = -1

    Const INSERT_STATEMENTS = 
        "INSERT INTO tbl(name, remarks)" & _
            ' OUTPUT句で挿入した行のidを返す
            "OUTPUT inserted.id" & _
                "VALUE('test4-1', 'test4-2')"
    Try
        cmd.Connection = con
        cmd.CommandType = cmd.CommandType ' 謎
        tran = conn.BeginTransaction()
        cmd.Transaction = tran 
        cmd.CommandText = INSERT_STATEMENT
        ' 返り値を一つだけ返す
        result = CInt(cmd.ExecuteScalar())
        tran.Commit()
    Catch ex As Exception
        Try
            tran.Rollback()
        End Try
    End Try
    return result
End Function
2
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
2
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?