Create your own SQL functions

Source: Internet
Author: User

# 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.