In a single user scenario, usually you could use the MAX function or order your receipts in DESCENDING order to find the last inserted one. Once you have this last record it is easy to extract the numeric part, increase the value by one and build the new receipt_no
Function GetNewReceiptNumber(prefix as string ) as String
using cn = new MySqlConnection(connectionstring)
using cmd = cn.CreateCommand()
cn.Open()
cmd.CommandText = "select receipt_no from receipts order by receipt_no DESC limit 1"
Dim result = cmd.ExecuteScalar
if result IsNot DbNull.Value AndAlso result IsNot Nothing Then
Dim number = Convert.ToInt32(result.ToString().SubString(prefix.Length))
return prefix & (number + 1).ToString("D6")
else
return prefix & "000001"
End If
End Using
End Using
End Function
or perhaps it is better to use MAX(receipt_no) for a slightly faster performance (but you really need to have an index of receipt_no)
cmd.CommandText = "select MAX(receipt_no) from receipts"
You could call this method from the code that tries to insert a new receipt in this way
Dim newReceiptNumber = GetNewReceiptNumber("BSP")
In this answer there are some assumptions:
- You have a global variable that keeps the details of your connection
string to MySql called
connectionstring
- The name of the table where you store the receipts is called
receipts