Auto Increment nvarchar value in vb.net

北城以北 提交于 2020-01-17 08:45:08

问题


I'm having a UserID field in my table and I need to get that value in my app and whenever I would like to add a new record it should increment by value '1'.

So this is how I'm trying to get the last ID enetered from my table.

For Example I'm having a value as "A000" and I need to increment that value by '1' so that it should become "A001" and so on..and after 'A999' as pointed out by PinnyM' it should become 'A1000'.

I don't want to write any stored procedures or anyother way from database.I would like to do it in a simpler way using my existing code.

 Dim strConnection As String = "Data Source=.\SqlExpress;Initial Catalog=Subscription;Integrated Security=True"
 Dim con As New SqlConnection(strConnection)
 con.Open()
 Dim comm As New SqlCommand
 comm.CommandText = "SELECT MAX(UserID) FROM Customers"
 comm.Connection = con
 Dim MaxUserID As Object = comm.ExecuteScalar()
 txtID.text=MaxUserID

回答1:


I got it managed to work by doing it this way:

Public Function IncrementString(ByVal Sender As String) As String
    Dim Index As Integer
    For Item As Integer = Sender.Length - 1 To 0 Step -1
        Select Case Sender.Substring(Item, 1)
            Case "000" To "999"
            Case Else
                Index = Item
                Exit For
        End Select
    Next
    If Index = Sender.Length - 1 Then
        Return Sender & "1" '  Optionally throw an exception ?
    Else
        Dim x As Integer = Index + 1
        Dim value As Integer = Integer.Parse(Sender.Substring(x)) + 1
        Return Sender.Substring(0, x) & value.ToString()
    End If
End Function



回答2:


Based on the comments above, I would propose:

comm.CommandText = "SELECT 'A' + RIGHT('000', CAST((MAX(primary_key) + 1) as nvarchar(255)), 3) FROM Customers"

What this does is:

  • Get the last key and add 1
  • Cast to nvarchar
  • Pad with 0's if necessary (up to 3 places)

I would absolutely not try to do this using a character based key as the UserID appears to be built. Also, note that this is not atomic and doesn't guarantee that another connection won't insert a row before you do. So it's really returning an optimistic value that may not be actually be correct. If this doesn't work for you, then consider letting IDENTITY do its work for you and get the value after the row was created using SCOPE_IDENTITY()



来源:https://stackoverflow.com/questions/14669252/auto-increment-nvarchar-value-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!