-5

I have a function in asp.net vb class file which generates a unique alphanumeric string.

After generating the string, I want to check if the string already exists in sql table, if so, I want to repeat the process.

Please find the code I am using

    Public Function GenerateUniqueID() As String    
     Dim numbers As String = "1234567890"
     Dim characters As String = numbers
     Dim length As Integer = 5
     Dim UID As String = String.Empty
     For i As Integer = 0 To length - 1
        Dim character As String = String.Empty
        Do
            Dim index As Integer = New Random().Next(0, characters.Length)
            character = characters.ToCharArray()(index).ToString()
        Loop While otp.IndexOf(character) <> -1
        UID += character
     Next

  '-----------
  check if UID already exist in db
  if yes

     repeat same function to generate new ID

  if no

     return unique id

   '-----------
     Return UID
End Function

I want to know how can I call same function if generated ID already exist in database.

4
  • 1
    So, what did you try? Commented Dec 14, 2017 at 9:02
  • 1
    Is your question "how do I query a SQL server in VB.NET"? Commented Dec 14, 2017 at 9:03
  • 1
    make your question more clear. Commented Dec 14, 2017 at 9:11
  • Possible duplicate of How to display query results from SQL server in VB? Commented Dec 14, 2017 at 9:40

1 Answer 1

0

Instead of generating the random string on the front end, try it in SQL Server itself. Try the following

DECLARE @UID NVARCHAR(255),@Row INT =0

WHILE ISNULL(@Row,0) =0
BEGIN
    SELECT @UID = NEWID()
    SELECT @Row = COUNT(1) FROM YourTable WHERE AlphaString = @UID

END

SELECT AlphaString = @UID
Sign up to request clarification or add additional context in comments.

11 Comments

I want to show a user friendly ID to user before saving to database. Like Ticket No : FH87-KJ98923. There should not be a duplicate for this ID in the table.
I have updated the answer, now it will return you a new id that does not exists in the table and return the value, you can display it to customer and insert it to the table once the customer approves
Sorry, the query is not executing. It is taking a long time.
@user7566865I removed 1 line accidentally, I've added that back, try now
what is NEW_ID, it is showing error. I have a function to generate unique id, is it possible to check that value against database and call same function repeatedly.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.