0

I have an attribute that I just added to my database to hold confirmation numbers. The only problem is they are all null so I am getting errors. Thus I need a method to generate random confirmation numbers (no duplicates). The column entries have a max size of varchar(20). Any ideas how to do this? Thanks

Solution:

        randNum = Replace(Guid.NewGuid().ToString(), "-", "")
        randNum = randNum.Substring(0, 19)
ewein
  • 2,695
  • 6
  • 36
  • 54
  • Any rules for the number apart from the length? Btw, what errors do you get? – Tim Schmelter May 15 '12 at 21:14
  • No, no rules. And just some other things I am doing require that the attribute is not null. I just need a good way to generate the numbers and to handle no duplicates. – ewein May 15 '12 at 21:17

2 Answers2

0

Did a minute of research and came across these examples.

Random numbers in VB: Random integer in VB.NET

Random numbers in SQL Server: http://www.sql-server-helper.com/tips/generate-random-numbers.aspx

If you don't want to use numbers that don't mean anything (if you're just filling columns to avoid errors), you can make your variable nullable on the .NET side so it can house a null value.

Dim MyInt? as Integer

EDIT:

You can create a GUID, remove the dashes and cut it down to 20 characters which is still pretty unlikely to be repeated.

EDIT #2: If you're using a stored procedure to perform these updates for new records/changing records (you should be), you can create the random number on the SQL side and return it as the OUTPUT variable. That will give you validation that the record was created/updated as well as giving you the confirmation to present on the .NET side.

Edit #3: myGuild.ToString().Replace("-","").SubString(0,20) should do the trick.

Community
  • 1
  • 1
Yatrix
  • 13,361
  • 16
  • 48
  • 78
-1

Try generating GUID this will be different always

Guid.NewGuid().ToString()
Esen
  • 973
  • 1
  • 21
  • 47
  • Your column is a Varchar column, not a Guid column. It's also 20 characters and GUIDs are 36 with hyphens, 32 without. I edited my above if you don't want to check what numbers you've used, which should only be a one time thing since you're filling column once, from the way it sounds. – Yatrix May 15 '12 at 21:41
  • Ya your right, I sense some truncated data. @Yatrix, right now I need to fill it, but I will be adding and changing values while I go along. – ewein May 15 '12 at 21:45
  • My point is, the only time it will be null is the one time you are filling it. When you change the values later, they will no longer be null. If you make it a Not Null column, you'll force the value to be filled each time. You can also add a default value of a random number in SQL, I would imagine. – Yatrix May 15 '12 at 21:47