Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Generate Random Unqiue Numbers in C#

public int GenPurchaseOrderNum()
{
    Random random = new Random();
    _uniqueNum = random.Next(13287, 21439);
    return UniqueNum;
}

I removed unique constraint from the PONumber column in the db because an employee should only generate P.O. # when the deal is set. Otherwise, P.O. # would have 0.

P.O. Number used to have unique constraint, this forces employee to generate P.O. in all cases so the db doesn't throw unique constraint error.

Since i removed the unique constraint, any quote doesn't have P.O. will carry 0 value. Otherwise, a unique value is generated for P.O. #. However, i don't have a unique constraint in db which makes it hard for me to know whether the application generated P.O. # is unique or not.

What should i do?

I hope my question is clear enough

like image 914
peace Avatar asked Jun 17 '10 19:06

peace


People also ask

How do you generate unique random numbers?

In a column, use =RAND() formula to generate a set of random numbers between 0 and 1.

How do you generate a random number between 1 and 10 in C?

In this program we call the srand () function with the system clock, to initiate the process of generating random numbers. And the rand () function is called with module 10 operator to generate the random numbers between 1 to 10. srand(time(0)); // Initialize random number generator.

What is difference between rand () and Srand ()?

The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.


1 Answers

A GUID is a bit high in the way of overhead. Specifically, it sounds like you need a human readable number for the PO#, which makes a GUID impractical. I'd be more inclined to use the following scenario.

  1. Remove any NOT NULL constraints you have on the field.
  2. Have a stored procedure that you use to create a new PO that leaves the PO # field NULL. Null is most appropriate in the case described since in the world of DB NULL means "unknown" and since you don't actually HAVE a PO #, it IS unknown.
  3. Use a stored procedure that updates the field when the deal is complete to increment to the next available PO number. This will happen server side, so it doesn't matter what client the update comes from it will still be unique to that table. This stored procedure can then return the updated result set (if required) to the client so they can see the new PO #.

That's the 20k foot view.

like image 195
Steve Brouillard Avatar answered Oct 19 '22 07:10

Steve Brouillard