Stored procedure
function The difference between stored procedure and function
Function can only return one variable limit. The stored procedure can return more than one.
Stored procedures can return parameters, while functions can only return values or table objects.
The stored procedure is generally executed as a separate part (EXEC execution), while the function can be called as a part of the query statement (SELECT call). Since the function can return a table object, it can be located in the FROM key in the query statement. behind the word.
Functions can be embedded in sql and used in select, but not stored procedures.
There are many restrictions on functions, such as temporary tables cannot be used, only table variables can be used. Some functions are not available, and so on. There are relatively few restrictions on stored procedures.
Table variables and temporary tables
Table variables:
DECLARE @tb table(id int identity(1,1), name varchar(100))
Temporary table:
SELECT name, address
INTO #ta FROM mytable
WHERE The name like 'zhang%'
temporary table uses the hard disk (tempdb database), and the table name variable occupies memory, so of course, the small amount of data means that the table variable in memory is faster. When there is a large amount of data, table variables cannot be used, which consumes too much memory. Temporary tables are suitable for large amounts of data.
Table variables have a clear scope and are automatically cleared at the end of the function, stored procedure or batch that defines the table variable.
Table variables do not need to be deleted, so there will be no naming conflicts. Temporary tables, especially global temporary tables, must resolve naming conflicts.
global temporary table
local temporary tables Those table names that begin
with a pound sign (#). These tables are only visible on the connection that created the local temporary table.
When a local temporary table is created within a stored procedure, the end of the stored procedure means that the local temporary table is dropped.
The current session ends, and all local temporary tables created within the session will be Dropped.
global temporary tables Those table names that begin
with two pound signs (##). Global temporary tables are visible on all connections. If these tables are not explicitly dropped before the connection that created them is broken, they are dropped as soon as all other tasks stop referencing them
. When the connection that created the global temporary tables is broken, new tasks can no longer reference them. As soon as the current statement is executed, the association between the task and the table is removed; therefore, normally, the global temporary table is removed as soon as the connection that created the global temporary
table is broken.
The global temporary table will be dropped after the session that created it ends. After the drop, other sessions will not be able to reference the global temporary table.
Foreign key constraints cannot be placed on temporary tables.
Correct deletion method:
-- Correct temporary table deletion operation
if object_id('tempdb..#tempTable') is not null Begin
drop table #tempTable
End
sql Determine whether the temporary table exists, delete the temporary table and rebuild
IF Object_id('Tempdb. .#dl') IS NOT NULL
DROP TABLE #dl -- drop the temporary table if it exists
CREATE TABLE #dl (neirong char(20),icount int, dlzonjine int, dlshu int, dlyin int) --Rebuild the temporary table
INSERT INTO #dl SELECT * FROM tab1 --Insert the data of the physical table into the temporary
table Custom function
Create UDF:
CREATE [AGGREGATE] FUNCTION function_name(parameter_name type,[parameter_name type,...])
RETURNS {STRING|INTEGER|REAL}
runtime_body
Simply put:
CREATE FUNCTION function name (parameter list)
RETURNS return value type
function body
Delete UDF:
DROP FUNCTION function_name
Call a custom function Syntax:
SELECT function_name(parameter_value,...)
DELIMITER // It means to modify the default terminator ";" is "//", and subsequent SQL statements must be "//" "As the end
CREATE FUNCTION IF EXIST deleteById(uid SMALLINT UNSIGNED)
RETURNS VARCHAR(20)
BEGIN
DELETE FROM son WHERE id = uid;
RETURN (SELECT COUNT(id) FROM son);
END//
If it contains multiple statements, we need to put multiple statements in the BEGIN...END statement block Define local in
the custom function Variable syntax:
DECLARE var_name[,varname]...date_type [DEFAULT VALUE]; in
simple terms:
DECLARE variable 1[, variable 2,...] variable type [DEFAULT default value]
The scope of these variables is in BEGIN ...END procedure
Stored procedure
Stored procedure is simply a collection of one or more MySQL statements saved for later use.
A stored procedure is a collection of business logic and processes. You can create tables, update data, delete and so on in the stored procedure.
Simple stored procedure
create procedure porcedureName ()
begin
select name from user;
end;
-- call procedure
call porcedureName ();
delete stored procedure
DROP PROCEDURE IF EXISTS porcedureName; --
stored procedure without parentheses () using parameters
create procedure procedureName(
out min decimal(8,2),
out avg decimal(8,2),
out max decimal(8,2)
)
BEGIN
select MIN(price) INTO min from order;
select AVG(price) into avg from order;
select MAX(price) into max from order;
END; the
call must match the parameters
call procedureName(@min, @avg, @max);
select @min, @avg, @max;
use the in parameter, enter a user id , which returns the total price of all orders for this user.
create procedure getTotalById (
in userId int,
out total decimal(8,2)
)
BEGIN
select SUM(r.price) from order r
where r.u_id = userId
into total;
END;
Call the stored procedure
call getTotalById(1, @total);
select @total;
Get all the order prices of the user according to the user id, and dynamically choose whether to add tax. The code is designed as follows
create procedure getTotalByUser2(
in userId int,
in falg boolean, -- whether to add tax mark
out total decimal(8,2)
)
begin
DECLARE tmptotal DECIMAL(8,2);
DECLARE taxrate int DEFAULT 6;-- default Taxable interest rate
select SUM(r.price) from order r
where r.u_id = userId
into tmptotal;
if taxable then
select tmptotal + (tmptotal/1000*taxrate) into tmptotal;
end if;
select tmptotal into total;
END;
call Process
call getTotalByUser2(1, false, @total); -- 不加税
call getTotalByUser2(1, true, @total); -- 加税
select @total;
IF ELSE 做为流程控制语句使用
IF search_condition THEN
statement_list
[ELSEIF search_condition THEN]
statement_list ...
[ELSE
statement_list]
END IF
create procedure dbname.proc_getGrade
(stu_no varchar(20),cour_no varchar(10))
BEGIN
declare stu_grade float;
select grade into stu_grade from grade where student_no=stu_no and course_no=cour_no;
if stu_grade>=90 then
select stu_grade,'A';
elseif stu_grade<90 and stu_grade>=80 then
select stu_grade,'B';
elseif stu_grade<80 and stu_grade>=70 then
select stu_grade,'C';
elseif stu_grade70 and stu_grade>=60 then
select stu_grade,'D';
else
select stu_grade,'E';
end if;
END
Note: IF is a statement. After END IF, a semicolon ";" needs to be added to indicate the end of the statement. Other statements such as CASE, LOOP, etc. are also the same.
SELECT
case gender
WHEN 1 THEN 'NAN'
WHEN 0 THEN 'NV'
end as gender
FROM
t_swidy_day_nutrient
First usage:
SELECT name,
CASE WHEN birthday < '1981' THEN 'old'
WHEN birthday > '1988' THEN 'yong'
ELSE 'ok'
SELECT NAME, CASE name
WHEN 'sam' THEN 'yong'
WHEN 'lee' THEN 'handsome'
ELSE 'good' END as oldname
FROM lee
第三种:当然了,case when 语句还可以复合
select name, birthday,
case
when birthday > '1983' then 'yong'
when name='lee' then 'handsome'
else 'just so so' end
from lee;
select payment_date, amount,
case
when amount >= 0 AND amount < 40 then 'low'
when amount >=40 AND amount < 80 then 'moderate'
when amount >=80 then 'high'
else 'null' END as dd
FROM penalties
http://www.cnblogs.com/xiangxiaodong/archive/2013/06/04/3116679.html Using
a function in MySQL to loop and splicing n strings after string one
delimiter $$
drop function if exists fun_addStr;
create function fun_addStr(str1 varchar(100),str2 varchar(10),num int) returns varchar(200)
begin
declare i int default 1;
declare result varchar(200) default '';
set result=str1;
myloop:loop
set i=i+1;
set result=concat(result,str2);
if i>num
then
leave myloop;
end if;
end loop myloop;
return result;
end $$
delimiter;
call
select fun_addStr('string 1', 'string 2', 3);
loop and leave, iterate to achieve loop
-- loop flag unconditional loop,
leave is similar to break statement, jump out of loop, jump out of begin end,
iterate is similar to continue, end this loop
DELIMITER $$
DROP PROCEDURE IF EXISTS LOOPLoopProc$$
CREATE PROCEDURE LOOPLoopProc()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = 1;
SET str = '';
loop_label: LOOP
IF x > 10 THEN
LEAVE loop_label;
END IF;
SET x = x + 1;
IF (x mod 2) THEN
ITERATE loop_label;
ELSE
SET str = CONCAT(str,x,',');
END IF;
END LOOP;
SELECT str;
END$$
DELIMITER ;
mysql stored procedure cursor query result loop
http://blog.csdn.net/cao478208248/article/ details/27642723
If the table does not exist to create this table, then you can directly use
create table if not exists tablename
create table if not exists like old_table_name;
select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='dbname' and TABLE_NAME='tablename' ;
drop table table name if exists table name;
//------------------------------------------------------ -
DROP TABLE IF EXISTS `Persons`;
CREATE TABLE `Persons` (
`Id_P` int(11) NULL DEFAULT NULL ,
`LastName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`FirstName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`Address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
`City` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
;
-- ----------------------------
-- Records of Persons
-- ----------------------------
BEGIN;
INSERT INTO `Persons` VALUES ('1', '111', '111', '111', '222'), ('2', '22', '222', '222', '222'), ('3', '33', '33', '33', '33');
COMMIT;
stored procedure function
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326078351&siteId=291194637
Recommended
Ranking