MySQL学习笔记三

? 注释

select 1+1; # 单行注释
select 1+1; – 单行注释
select 1 / 多行注释 / + 1;
? 基本数据类型操作

字符串
select ‘hello’, ‘“hello”‘, ‘“”hello””‘, ‘hel’’lo’, ‘/‘hello’;
select “hello”, “‘hello’”, “‘’hello’’”, “hel””lo”, “/“hello”;

/n换行
select ‘This/nIs/nFour/nLines’;

/转义
select ‘hello / world!’;
select ‘hello /world!’;
select ‘hello // world!’;
select ‘hello /‘ world!’;
? 设置数据库mode模式

SET sql_mode=’ANSI_QUOTES’;
create table t(a int);
create table “tt”(a int);
create table “t””t”(a int);
craate talbe tab(“a””b” int);
? 用户变量

set @num1 = 0, @num2 = 2, @result = 0;

select @result := (@num1 := 5) + @num2 := 3, @num1, @num2, @result;

? 存储过程

创建存储过程:
delimiter //
create procedure get(out result int)
begin
select max(age) into result from temp;
end//
调用存储过程:
call get(@temp);
查询结果:
select @temp;

删除存储过程:
drop procedure get;

查看存储过程创建语句:
show create procedure get;

select…into 可以完成单行记录的赋值:
create procedure getRecord(sid int)
begin
declare v_name varchar(20) default ‘jason’;
declare v_age int;
declare v_sex bit;
select name, age, sex into v_name, v_age, v_sex from temp where id = sid;
select v_name, v_age, v_sex;
end;
call getRecord(1);
? 函数

函数类似于存储过程,只是调用方式不同
例如:select max(age) from temp;

创建函数:
create function addAge(age int) returns int
return age + 5;

使用函数:
select addAge(age) from temp;

删除函数:
drop function if exists addAge;
drop function addAge;

显示创建语法:
show create function addAge;
? 游标

声明游标:declare cur_Name cursor for select name from temp;
打开游标:open cur_Name;
Fetch游标:fetch cur_Name into @temp;
关闭游标:close cur_Name;

示例:
CREATE PROCEDURE cur_show()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE v_id, v_age INT;
DECLARE v_name varchar(20);
DECLARE cur_temp CURSOR FOR SELECT id, name, age FROM temp;
DECLARE CONTINUE HANDLER FOR SQLSTATE ‘02000’ SET done = 1;

OPEN cur_temp;

REPEAT
FETCH cur_temp INTO v_id, v_name, v_age;
IF NOT done THEN
IF isnull(v_name) THEN
update temp set name = concat(‘test-json’, v_id) where id = v_id;
ELSEIF isnull(v_age) THEN
update temp set age = 22 where id = v_id;
END IF;
END IF;
UNTIL done END REPEAT;

CLOSE cur_temp;
END
? 触发器

触发器分为insert、update、delete三种触发器事件类型
还有after、before触发时间
创建触发器:
create trigger trg_temp_ins
before insert
on temp for each row
begin
insert into temp_log values(NEW.id, NEW.name);
end//

删除触发器:
drop trigger trg_temp_ins
版权维护转载hoojo博客的。