一个简单的MySQL存储过程
delimiter //
CREATE PROCEDURE `dataUpdate`()
begin
declare allOr int;
declare oUUID varchar(32);
declare degree decimal(10,2);
declare oInfoCursor cursor for select o_uuid, degree from t_testA;
select count(1) into allOr from t_testA;
open oInfoCursor;
lp:loop
if allOr = 0 then
leave lp;
end if;
fetch oInfoCursor into oUUID, degree;
update t_testB set power = degree where ouuid = oUUID;
set allOr = allOr - 1;
end loop;
commit;
close oInfoCursor;
end //
delimiter ;
call dataUpdate();
update join
update test_a ta, test_b tb set ta.col1 = tb.col4 where ta.id = tb.id;
修改字段类型(多个字段使用一条sql)
alter table t_elec modify column fee decimal(10,8) default 0 comment '电费', modify column degree decimal(10,8) default 0 comment '度数';
为表新增字段
alter table t_ele add user_id integer not null default 0 comment '用户id';
将一个表的数据搬迁到另一个表中,备份表
-- 表t_elec必须存在,将表t_elec_1015数据插入到t_elec中
insert into t_elec select * from t_elec_1015;
-- 将t_elec数据备份到表t_elec_1015中
create table t_elec_1015 select * from t_elec;
--创建备份表,不搬迁原表数据
create table t_elec_1015 select * from t_elec where 1=2;
--复制表结构,完全复制表结构包含表的索引和约束,以上两种方法只能复制表的字段
create table t_elec_1015 like t_elec;
--将表数据输出到文件中,一般都没有权限,需要设置权限
select * into outfile "c:\\oa.txt" from oa_datajur;
创建表
CREATE TABLE t_elec (
uuid varchar(32) NOT NULL COMMENT '唯一标识',
fee varchar(32) DEFAULT NULL COMMENT '费用',
degree varchar(32) DEFAULT NULL COMMENT '度数',
creator varchar(32) DEFAULT NULL COMMENT '创建者',
create_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time timestamp NULL DEFAULT NULL COMMENT '修改时间',
updater varchar(32) DEFAULT NULL COMMENT '更新者',
PRIMARY KEY (uuid) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='电费表';
MySQL时间格式转换
select * from t_elec where create_time < STR_TO_DATE('2019-09-15 00:00:00','%Y-%m-%d %H:%i:%s')