views:

41

answers:

2

I have this sql

select concat( char(FLOOR(97+ RAND()*26))
                   , char(FLOOR(97+ RAND()*26))
                   , FLOOR(100+ RAND()*999)
                   , char(FLOOR(97+ RAND()*26))) AS randomcode 
WHERE NOT EXISTS (
       SELECT *
       FROM table
       WHERE code_felt = randomcode );

But I can't get it to work. Does somebody know what I am doing wrong here?

I need to make a 6 chart code in random and it does not exists in my code. I hope I can be helped.

A: 

Try this:

select CONCAT(char(rand()*26+65),char(rand()*26+65));
catwalk
yes? now i only need to search for a code when its not in use in my code table. :)
NeoNmaN
@NeoNmaN: I doubt it is possible to accomplish is plain SQL - you will probably need a stored procedure that will generate those id in a loop, until it finds a unique one
catwalk
+1  A: 

You have to select FROM somewhere. Your SELECT does not have a table name. Since you don't actually select random values from a table, you should use DUAL (this is a 'fake' table):

select concat(
  char(97+ RAND()*26),
  char(97+ RAND()*26),
  floor(100+rand()*900),
  char(97+ RAND()*26)) 
as randomcode from dual
  WHERE NOT EXISTS (SELECT * FROM table WHERE code_felt = randomcode );

This will sometimes select one record, sometimes no records. If it selects no records, you have to repeat the query, I can't think of a way to make it always select one record.

yu_sha
perfeket, and tanks i dont know i can use dual table ( fake ) relly nice and tanks a lot :)
NeoNmaN
if i only whst a-z in random carh can you help me whit this to? :)
NeoNmaN
(97+ RAND()*26) - this is a-z, you got it right.
yu_sha