0

i have this code

 With ServiceInformationDialog


        Dim cmd As New SqlCommand
        Dim id As Integer
        cn.Open()
        cmd.Connection = cn
        cmd.CommandText = " SELECT MAX(Service_ID) FROM Table_Service"

        If IsDBNull(cmd.ExecuteScalar) Then

            id = 1
            .ServiceIDserviceTextBox1.Text = id
        Else
            id = cmd.ExecuteScalar + 1
            .ServiceIDserviceTextBox1.Text = id

        End If
        cmd.Dispose()
    End With

    cn.Close()

it work but i want to make it as a function, so i can use it all over my project, and i want to know how to make it ?

Callum Linington
  • 14,213
  • 12
  • 75
  • 154
user3198588
  • 43
  • 3
  • 10

2 Answers2

1

Modules in VB are typically used for utility functions such as this - I don't know where 'cn' resides, so you'll have to figure that out, in addition to naming the module something more meaningful for your application:

Friend Module Utility
    Public Function MaxServiceID(ByVal column As String, ByVal table As String) As Integer
        Dim cmd As New SqlCommand
        cn.Open()
        cmd.Connection = cn
        cmd.CommandText = " SELECT MAX(" & column & ") FROM " & table

        Dim id As Integer
        If IsDBNull(cmd.ExecuteScalar) Then
            id = 1
        Else
            id = cmd.ExecuteScalar + 1
        End If

        cmd.Dispose()
        cn.Close()

        Return id
    End Function
End Module

Then you would have:

ServiceInformationDialog.ServiceIDserviceTextBox1.Text = Utility.MaxServiceID("Service_ID", "Table_Service")
Dave Doknjas
  • 6,394
  • 1
  • 15
  • 28
0

When you retrieve an ID like that, other user may have already inserted a record with such an ID, so you will get a unique key violation error, when trying to insert your record, due to concurrency issue.

A good way to do this, is to let DB handle your unique ID, for MSSQL, usually an IDENTITY column is used, for Oracle 10/11g you can use triggers, and 12c supports this feature out of the box. Then retrieve an ID of the already inserted record (if you need it for some reason). For SQL, see:

Community
  • 1
  • 1
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151