c# - Recursively checking for a duplicate random number in a database -
i create random number , check if exists in database table. if does, generate 1 , check again, following work?
public int generatenumber() { random r = new random(); int num = r.next(1000); //psuedo-code if(num in table) generatenumber(); return num; }
it seems based on answers below recursion should avoided here , should auto-increment number, alternative either start auto-increment @ 1 , pad 0's until is 8 characters long or start @ 10,000,000.
also, if datatype has varchar(8). how can auto-increment number, store in in varchar(8)?
this not problem needs solved recursion. not mention fact if have fair few numbers in database, , loops lots of times, you'll stack overflow error. why not change iterative function:
public int generatenumber() { random r = new randon(); int num = r.next(1000); while(num in database) { num = r.next(1000); } return num; }
different approach, while i'm here
why not implement transitive difference between these values? i.e: first number one, 2 etc. need recent entry, , add 1 it. no need consistently keep making database queries.
Comments
Post a Comment