bigLiBox

備忘録だったり。読書メモだったり。ところで仕事が終わりそうにないんですが。

ExceptionからSQL Server の一意制約違反を検知する

システム用のExceptionクラス(hogeException)がありまして。
共通処理はExceptionすべてhogeException型にして投げてくる。

クエリを実行する共通処理があって、
Exceptionの中でも一意制約エラーが発生した場合を検知したい。

これでいけたらいいんだけど・・・。

 Private Function InsertRecord(ByVal dataRecordInfo() As String, ByVal insertColumnIchi As Dictionary(Of String, Integer)) As Integer
        Dim effectCount As Integer = 0     '影響を受けた行数

        Dim sql As String = "INSERT INTO [TMP_TABLE] ([CODE],[VALUE]) VALUES (@Code ,@Value)"

        Try
                effectCount = Me.CommonLogic.ExecDBQuery(sql, paramNames, paramValues, paramTypes, -1)
            Catch hogeEx As hogeException
                If Not IsNothing(hogeEx.InnerException) Then
                    Dim ex As Exception = GetInnerException(hogeEx.InnerException)
                    If TypeOf ex Is SqlException Then
                        If CType(ex, SqlException).Number = 2627 Then
                            'レコード登録時に、一意制約エラーが発生した場合
                            Console.WriteLine("一意制約エラー発生")
                            Exit Try
                        End If
                    End If
                End If

                Throw New hogeException("エラーID", hogeEx)
            End Try
            Return effectCount
    End Function

    Private Function GetInnerException(ex As Exception) As Exception
        If IsNothing(ex.InnerException) Then
            Return ex
        End If
        Return GetInnerException(ex.InnerException)
    End Function
  • 参考

GridViewのRowUpdatedでPRIMARY KEY違反をハンドルする方法