MySql Stored Procedure learning summary attached pdf Document Download

Source: Internet
Author: User
Tags decimal to binary mysql command line

A stored procedure is a program stored in a database (just like a subroutine in a regular language). To be precise, MySql supports two types of "routine (routine: one is the stored procedure, and the other is the function that can return values in other SQL statements (like the functions pre-loaded by mysql, such as pi ()).

A stored procedure includes a name, a list of parameters, and a set of SQL statements that can contain many SQL statements. Here, we have a new syntax definition for local variables, exception handling, loop control, and if condition statements.

The following is an instance statement that includes a stored procedure:Copy codeThe Code is as follows: create procedure procedurel/* name stored PROCEDURE name */
(IN parameter1 INTEGER)/* parameters parameter */
BEGIN/* start of blokc statement header */
DECLARE variable1 CHAR (10);/* variables variable Declaration */
IF parameter1 = 17 THEN/* start of IF condition start */
SET variable1 = 'birds ';/* assignment value */
End if;/* end of if end */
Insert into table1 VALUES (variable1);/* statement SQL statement */
END/* end of block statement block END */

MySQL version: 5.0.45 phpMyAdmin version: 2.11.3
First, read the syntax for creating a stored procedure in MySQL 5.0 reference manual:
CREATE
[DEFINER = {user | CURRENT_USER}]
PROCEDURE sp_name ([proc_parameter [,...])
[Characteristic...] routine_body
Proc_parameter:
[IN | OUT | INOUT] param_name type
Type:
Any valid MySQL data type
Characteristic:
LANGUAGE SQL
| [NOT] DETERMINISTIC
| {Contains SQL | no SQL | reads SQL data | modifies SQL DATA}
| SQL SECURITY {DEFINER | INVOKER}
| COMMENT 'string'
Routine_body:
Valid SQL procedure statement
If you are not familiar with MySQL, simply reading this syntax structure is certainly not enough for MySQL Stored Procedure programming. I used ms SQL server before, so the following records my familiarity with the MySQL stored procedure are also a major difference between ms SQL SERVER and MySQL.
The first step is to write a Hello Word stored procedure as follows:Copy codeThe Code is as follows: create procedure phelloword ()
BEGIN
SELECT 'Hello Word! 'As F;
END;

Copy the statement used to create the phelloword stored procedure to phpMyAdmin and run the command. The following error is returned:
#1064-You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''at line 3
I have been entangled for a long time in this issue. The execution in MySQL command line tool is also not successful, but according to the prompt information, we can know that the execution in SELECT 'Hello Word! 'As F; ends, followed by END; not executed, which obviously leads to errors.
Select a separator. The syntax is as follows: DELIMITER //
The Delimiter is the symbol that notifies the MySQL client that the input is complete. ";" Is always used, but not in the stored procedure, because many statements in the Stored Procedure require semicolons.
Therefore, the above stored procedure is changed:Copy codeThe Code is as follows: create procedure ptest ()
BEGIN
SELECT 'Hello Word! 'As F;
END //

In addition, when executing in phpMyAdmin, enter // In the Delimiter text box. This stored procedure can be created successfully.
Step 2: Write a complete stored procedure that includes parameters, variables, variable assignment, condition judgment, UPDATE statements, and SELECT returned result set, as follows:Copy codeThe Code is as follows: create procedure plogin
(
P_username char (15 ),
P_password char (32 ),
P_ip char (18 ),
P_logintime datetime
)
LABEL_PROC:
BEGIN
DECLARE v_uid mediumint (8 );
DECLARE v_realpassword char (32 );
DECLARE v_nickname varchar (30 );
DECLARE v_oltime smallint (6 );
SELECT u. uid, u. password, f. nickname, u. oltime INTO v_uid, v_realpassword, v_nickname, v_oltime
FROM cdb_members u inner join cdb_memberfields f ON f. uid = u. uid WHERE u. username = p_username;
IF (v_uid is null) THEN
SELECT 2 AS ErrorCode;
LEAVE LABEL_PROC;
End if;
IF (p_password <> v_realpassword) THEN
SELECT 3 AS ErrorCode;
LEAVE LABEL_PROC;
End if;
UPDATE ipsp_userexpands SET lastloginip = p_ip, lastlogintime = p_logintime WHERE uid = v_uid;
SELECT 0 AS ErrorCode, v_uid AS uid, v_nickname AS nickname, v_oltime AS oltime;
END LABEL_PROC //

The first thing to talk about is the syntax for assigning values to variables. MySQL uses SELECT u. uid, u. password, f. nickname, u. oltime INTO v_uid, v_realpassword, v_nickname, v_oltime FROM cdb_members u inner join cdb_memberfields f ON f. uid = u. uid WHERE u. username = p_username; assign a value to the variable.
The second is the syntax structure of condition judgment, as shown below:Copy codeThe Code is as follows: IF... THEN
...;
ELSE
IF... THEN
...;
ELSEIF
...;
ELSE
...;
End if;
End if;

Finally, let's talk about the use of LEAVE syntax. When a certain condition is met and the following SQL statement is not executed, the RETURN syntax is used in ms SQL SERVER. in MySQL, the corresponding keyword is not found, however, the LEAVE syntax can be used to meet the requirements. Define a label before the BEGIN of the stored procedure, for example, "LABEL_PROC:", and then run "LEAVE LABEL_PROC" where the RETURN is interrupted;.
Step 3: Create a stored procedure for executing dynamic SQL statements.Copy codeThe Code is as follows: create procedure ipsp_getresourcedir
(
P_hashcode char (40)
)
LABEL_PROC:
BEGIN
DECLARE v_ SQL varchar (200 );
SET v_ SQL = CONCAT ('select filedir FROM ipsp_resources WHERE hashcode = \ '', p_hashcode, '\ 'limit 0, 1 ');
SET @ SQL = v_ SQL;
PREPARE sl FROM @ SQL;
EXECUTE sl;
Deallocate prepare sl;
END LABEL_PROC //

Here we mention that "\" is an escape character. The concatenated SQL statement is similar to SELECT filedir FROM ipsp_resources WHERE hashcode = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' LIMIT 0, 1
In addition, @ SQL is a user variable. For detailed usage, see the MySQL reference manual.
If you have experience writing stored procedures on ms SQL server, after reading these, I think the basic MySQL Stored Procedure programming should be able to cope with it!
For more information, see the MySQL reference manual or related books!

Mysql 5.0 Stored Procedure learning Summary (more details)

1. Create a stored procedure
1. Basic Syntax:

Create procedure sp_name ()
Begin
.........
End
2. parameter transfer
Ii. Call the Stored Procedure
1. Basic Syntax: call sp_name ()
Note: The stored procedure name must be enclosed in parentheses, even if the stored procedure has no parameters
Iii. delete stored procedures
1. Basic Syntax:
Drop procedure sp_name //
2. Notes
(1) You cannot delete another stored procedure in one stored procedure. You can only call another stored procedure.
4. blocks, conditions, and loops

1. Block definition, commonly used
Begin
......
End;
You can also create an alias for the block, such:
Lable: begin
...........
End lable;
You can use leave lable to jump out of the block and execute code after the block.
2. conditional statements

If condition then
Statement
Else
Statement
End if;
3. Loop statements
(1). while Loop
[Label:] WHILE expression DO
Statements
End while [label];

(2) loop

[Label:] LOOP
Statements
End loop [label];

(3). repeat until Loop

[Label:] REPEAT
Statements
UNTIL expression
End repeat [label];

5. Other Common commands
1. show procedure status
Displays basic information about all stored procedures in the database, including the database, stored procedure name, and creation time.
2. show create procedure sp_name
Displays detailed information about a stored procedure.

Operators used in mysql stored procedures
Mysql Stored Procedure learning Summary-Operators
Arithmetic Operators
+ Add SET var1 = 2 + 2; 4
-Subtract SET var2 = 3-2; 1
* Multiply by SET var3 = 3*2; 6
/Except SET var4 = 10/3; 3.3333
DIV Division SET var5 = 10 DIV 3; 3
% Modulo SET var6 = 10% 3; 1
Comparison Operators
> Greater than 1> 2 False
<Less than 2 <1 False
<= Less than or equal to 2 <= 2 True
>=Greater than or equal to 3> = 2 True
BETWEEN is 5 BETWEEN two values BETWEEN 1 AND 10 True
Not between two values 5 not between 1 AND 10 False
IN the set, 5 IN (,) is False.
Not in is not in the set 5 not in (,) True
= Equal to 2 = 3 False
<> ,! = Not equal to 2 <> 3 False
<=> Strictly compare whether two NULL values are equal NULL <=> NULL True
LIKE simple pattern matching "Guy Harrison" LIKE "Guy %" True
REGEXP regular expression match "Guy Harrison" REGEXP "[Gg] reg" False
Is null 0 is null False
Is not null 0 is not null True
Logical operators
AND)

AND

TRUE

FALSE

NULL

TRUE

TRUE

FALSE

NULL

FALSE

FALSE

FALSE

NULL

NULL

NULL

NULL

NULL

OR (OR)

OR

TRUE

FALSE

NULL

TRUE

TRUE

TRUE

TRUE

FALSE

TRUE

FALSE

NULL

NULL

TRUE

NULL

NULL

Exclusive or (XOR)

XOR

TRUE

FALSE

NULL

TRUE

FALSE

TRUE

NULL

FALSE

TRUE

FALSE

NULL

NULL

NULL

NULL

NULL

Bitwise operators

| Bit or
& Bit and
<Left shift
> Right shift
~ Bitwise non (single object operation, bitwise inversion)

Common functions in mysq stored procedures, string operations, mathematics, and date and time.

Mysql stored procedure basic functions
I. string type

CHARSET (str) // returns the string Character Set
CONCAT (string2 [,...]) // connection string
INSTR (string, substring) // returns the position of the first occurrence of the substring in the string. If no position exists, 0 is returned.
LCASE (string2) // converts it to lowercase
LEFT (string2, length) // take the length from the LEFT of string2
LENGTH (string) // string LENGTH
LOAD_FILE (file_name) // read content from the file
LOCATE (substring, string [, start_position]) is the same as INSTR, but the start position can be specified.
LPAD (string2, length, pad) // repeat pad to start with string until the string length is length
LTRIM (string2) // remove leading Spaces
REPEAT (string2, count) // REPEAT count times
REPLACE (str, search_str, replace_str) // REPLACE search_str with replace_str in str
RPAD (string2, length, pad) // use pad after str until the length is length.
RTRIM (string2) // remove backend Spaces
STRCMP (string1, string2) // compare the size of two strings by character,
SUBSTRING (str, position [, length]) // starts from the position of str and takes length characters,
Note: When processing strings in mysql, the default subscript of the first character is 1, that is, the parameter position must be greater than or equal to 1.

Mysql> select substring ('abcd );
+ -------- +
| Substring ('abcd',) |
+ -------- +

+ -------- +
1 row in set (0.00 sec)

Mysql> select substring ('abcd', 1, 2 );
+ -------- +
| Substring ('abcd', 1, 2) |
+ -------- +
| AB |
+ -------- +
1 row in set (0.02 sec)
TRIM ([[BOTH | LEADING | TRAILING] [padding] FROM] string2) // remove the specified character FROM the specified position
UCASE (string2) // converts to uppercase
RIGHT (string2, length) // gets the last length character of string2
SPACE (count) // generate count Spaces

Ii. Mathematics

ABS (number2) // absolute value
BIN (decimal_number) // convert decimal to binary
CEILING (number2) // rounded up
CONV (number2, from_base, to_base) // hexadecimal conversion
FLOOR (number2) // round down
FORMAT (number, decimal_places) // number of reserved decimal places
HEX (DecimalNumber) // convert to hexadecimal
Note: HEX () can input a string, returns its ASC-11 code, such as HEX ('def ') returns 4142143
You can also input a decimal integer to return its hexadecimal encoding. For example, HEX (25) returns 19.
LEAST (number, number2 [,...]) // calculates the minimum value.
MOD (numerator, denominator) // evaluate the remainder
POWER (number, power) // Exponent
RAND ([seed]) // Random Number
ROUND (number [, decimals]) // rounding, decimals is the number of decimal places]

Note: The return type is not an integer, for example:
(1) The default value is integer.
Mysql> select round (1.23 );
+ ----- +
| Round (1.23) |
+ ----- +
| 1 |
+ ----- +
1 row in set (0.00 sec)

Mysql> select round (1.56 );
+ ----- +
| Round (1.56) |
+ ----- +
| 2 |
+ ----- +
1 row in set (0.00 sec)

(2) the number of decimal places can be set to return floating point data.
Mysql> select round (1.567, 2 );
+ ------ +
| Round (1.567, 2) |
+ ------ +
| 1, 1.57 |
+ ------ +
1 row in set (0.00 sec)

SIGN (number2) // return SIGN, positive and negative or 0
SQRT (number2) // Square

Iii. Date and Time

ADDTIME (date2, time_interval) // Add time_interval to date2
CONVERT_TZ (datetime2, fromTZ, toTZ) // convert the time zone
CURRENT_DATE () // current date
CURRENT_TIME () // current time
CURRENT_TIMESTAMP () // current Timestamp
DATE (datetime) // return the DATE part of datetime
DATE_ADD (date2, INTERVAL d_value d_type) // Add a date or time in date2
DATE_FORMAT (datetime, FormatCodes) // display datetime in formatcodes format
DATE_SUB (date2, INTERVAL d_value d_type) // subtract a time from date2
DATEDIFF (date1, date2) // two date differences
DAY (date) // returns the DAY of the date
DAYNAME (date) // english week
DAYOFWEEK (date) // Week (1-7), 1 is Sunday
DAYOFYEAR (date) // The day of the year
EXTRACT (interval_name FROM date) // EXTRACT the specified part of the date FROM date
MAKEDATE (year, day) // specifies the day of the year and year to generate a date string.
MAKETIME (hour, minute, second) // generate a time string
MONTHNAME (date) // name of the English month
NOW () // current time
SEC_TO_TIME (seconds) // converts seconds to time
STR_TO_DATE (string, format) // convert string to time, which is displayed in format
TIMEDIFF (datetime1, datetime2) // two time difference
TIME_TO_SEC (time) // time to seconds]
WEEK (date_time [, start_of_week]) // WEEK
YEAR (datetime) // YEAR
DAYOFMONTH (datetime) // The day of the month
HOUR (datetime) // HOUR
LAST_DAY (date) // the last date of the Month of date
MICROSECOND (datetime) // MICROSECOND
MONTH (datetime) // MONTH
MINUTE (datetime) // MINUTE

Appendix: available types in INTERVAL
DAY, DAY_HOUR, DAY_MINUTE, DAY_SECOND, HOUR, HOUR_MINUTE, HOUR_SECOND,

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.