# randomly generated string
#rand_string (n int) rand_string is the function name (n int)//The function receives an integer
Create function rand_string (n INT)
Returns varchar (255) #该函数会返回一个字符串
Begin
#chars_str定义一个变量 Chars_str, the type is varchar (100), the default value ' ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFJHIJKLMNOPQRSTUVWXYZ ';
DECLARE chars_str varchar (+) Default
' ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFJHIJKLMNOPQRSTUVWXYZ ';
DECLARE return_str varchar (255) default ';
declare i int default 0;
While I < n do
Set Return_str =concat (return_str,substring (Chars_str,floor (1+rand () *52), 1));
Set i = i + 1;
End while;
return return_str;
End
# randomly generated department number
Delimiter $$
Drop function Rand_num $$
#这里我们又自定了一个函数
Create function Rand_num ()
returns INT (5)
Begin
declare i int default 0;
Set i = Floor (10+rand () *500);
return i;
End $$
Examples of use in PHP:
$con =mysql_connect (' localhost ', ' root ', ' password ');
if (! $con) {die (' connection failed ');}
mysql_select_db (' temp ');
$sql = "Select Rand_string (6) as rand_string from dual;" Dual table is the sub-table, the actual non-existent table
$res = mysql_query ($sql. $con);
if ($res = = Mysql_fetch_assoc ($res)) {
Echo $res;
}
Create your own SQL functions