表整体(table )操作

针对数据库的表进行新增操作,考虑到脚本可重复执行,有以下两种方案

  • 使用tryaddtable存储过程
call tryaddtable('act_ge_property', 'create table act_ge_property  (
  name_ varchar(128) character set utf8 collate utf8_general_ci not null,
  value_ varchar(600) character set utf8 collate utf8_general_ci null default null,
  rev_ decimal(22, 0) null default null,
  primary key (name_) using btree,
  index sys_c001769640(name_) using btree
) engine = innodb character set = utf8 collate = utf8_general_ci row_format = dynamic;')
  • 使用原生判断语句
create table if not exists act_ge_property  (
  name_ varchar(128) character set utf8 collate utf8_general_ci not null,
  value_ varchar(600) character set utf8 collate utf8_general_ci null default null,
  rev_ decimal(22, 0) null default null,
  primary key (name_) using btree,
  index sys_c001769640(name_) using btree
) engine = innodb character set = utf8 collate = utf8_general_ci row_format = dynamic;

使用以上两种方式可能存在一个问题,就是数据库中存在一个表结构不同的表,此时以上的语句其实就是无效的,很多人都会采用先删表然后再建表的方式,如下所示

drop table if exists act_ge_property;
create table act_ge_property  (
  name_ varchar(128) character set utf8 collate utf8_general_ci not null,
  value_ varchar(600) character set utf8 collate utf8_general_ci null default null,
  rev_ decimal(22, 0) null default null,
  primary key (name_) using btree,
  index sys_c001769640(name_) using btree
) engine = innodb character set = utf8 collate = utf8_general_ci row_format = dynamic;

但是删除表是存在巨大风险的,如果只是一些缓存表倒还好,如果是存放重要业务数据或者参数信息的表,删除表会导致程序运行失败。所以是不允许直接删除表的,那么如何避免数据库存在同样表名而结构不同呢?可以考虑在建表语句后面添加一个查询语句,其中包含完整的字段。

select name_,value_,rev_ from act_ge_property limit 0,1;

一旦表结构不一致,就需要考虑针对表字段的增删操作以及数据同步操作。

删除表的操作是存在巨大风险的,删除表之前必须准备评估是否导致业务数据丢失的问题。

表字段(column )操作

  • 新增表字段

通过tryaddtabcolumn存储过程保证可重复执行。

call tryaddtabcolumn('act_ge_property','value_ ','varchar(600) character set utf8 collate utf8_general_ci null default null');
  • 修改表字段

原生语句已经支持可重复执行,直接使用即可

alter table act_ge_property modify column value_ varchar(200) character set utf8 collate utf8_general_ci null default null;
  • 删除表字段

删除表字段同样是存在巨大风险的,需要仔细评估。可能会涉及的场合就是将某个字段替换为另一个字段(二者名称不一致)。通过先删除字段然后再添加字段会导致原来数据丢失,mysql中可以通过alter table change语句来修改字段。但是没法保证可重复性。

-- 将act_ge_property字段value_的名字修改为value2_
-- 对应的mysql原语句 alter table act_ge_property change value_ value2_ varchar(200) character set utf8 collate utf8_general_ci null default null;
call trychangetabcolumn('act_ge_property','value_','value2_','varchar(200) character set utf8 collate utf8_general_ci null default null');
-- 将act_ge_property字段value2_的名字修改为value_
call trychangetabcolumn('act_ge_property','value2_','value_','varchar(200) character set utf8 collate utf8_general_ci null default null');

表索引(index )操作

  • 添加索引

主要考虑可重复执行问题,首先通过trydropindex删除索引。然后再创建索引

-- 创建普通索引
call trydropindex('act_ge_property','idx_rev_');
create index idx_rev_ on act_ge_property (rev_ asc)  using btree;
-- 创建唯一索引
call trydropindex('act_ge_property','idx_value_');
create unique index idx_value_ on act_ge_property (value_ asc)  using btree;
-- 多个字段的索引
call trydropindex('act_ge_property','idx_value_rev_');
create unique index idx_value_rev_ on act_ge_property (value_ asc,rev_ asc)  using btree;
  • 删除索引

考虑可重复执行问题,直接使用存储过程。

call trydropindex('act_ge_property','idx_rev_');
call trydropindex('act_ge_property','idx_value_');
call trydropindex('act_ge_property','idx_value_rev_');

表数据操作

  • 新增数据

绝大多数的表新增数据都只需考虑先根据主键或者关键字删除,然后插入数据即可。如下所示

delete from act_ge_property where name_ in('next.dbid','schema.history','schema.version');
insert into act_ge_property(name_, value_, rev_) values ('next.dbid', '1215401', 12155);
insert into act_ge_property(name_, value_, rev_) values ('schema.history', 'create(5.15.1)', 1);
insert into act_ge_property(name_, value_, rev_) values ('schema.version', '5.15.1', 1);
commit;

以上表是没有数字型的主键的,如果涉及到数据型主键的,有两种方案:

第一种采用主键自增,只用在表结构定义的时候将主键字段设置为auto_increment即可。

第二种模仿oracle中的序列,在mysql中通过表sequence维护这些序列信息。在插入数据的时候,需要通过存储过程getsequencenextval获取序列值(其中s_tsys_customer对应sequence表的seq_name字段)

delete from tsys_customer where s_code = 'py2022';
insert into `tsys_customer`(`s_id`, `s_code`, `c_code`, `c_name`) values (getsequencenextval('s_tsys_customer'),  'py2022', 'pufa_bank', '浦银自营');
commit;

但是有部分的表是不允许这样操作的,比如tpara表、sequence表。前者在规范(http://191.168.0.126/svn/xir_web_j2ee/2.银行资管/文档/技术文档/脚本规范/初始化tpara数据脚本规范.html)中已经详述,后者在规范(http://191.168.0.126/svn/xir_web_j2ee/2.银行资管/文档/技术文档/脚本规范/mysql序列操作规范.html)中详述。

tpara表新增数据

call tryexcuteifnotexists('tpara','p_code','isusedinstverifyapproval','
 insert into tpara(p_id, p_name, p_code, p_value, p_value_name, p_type, p_isvisible, p_enum_value, p_enum_type, p_ismulti, p_creat_date, p_remark) values (''31020'', ''是否使用指令验证审批流程'', ''isusedinstverifyapproval'', ''false'', ''否'', ''3'', ''1'', ''true_是@false_否'', ''1'', ''0'', ''20171124'', null)
');

sequence表新增数据

call tryaddsequence('s_ttrd_auth_portal_config', 'insert into sequence(seq_name, current_val, increment_val, min_val, max_val, cache_size) values (''s_ttrd_auth_portal_config'', 1, 1, 0, 9223372036854775807, 20)');

新增表数据类似于初始化操作,如果这个数据不会变化,无论操作多少次都是一样的,先删除后插入没有任何问题。但是这个数据可能会被修改的时候,就要考虑你的脚本会不会因为重复执行导致业务没法操作了。比如序列初始化的时候是1,然后在程序里使用了一段时间,再次执行你的脚本,数据库的序列值回去了,程序肯定会报错的(对应的主键值已经存在了)。

function 函数操作

drop function if exists gzb_get_precision_value;
-- 在创建函数语句前修改默认分割符
delimiter $
create function gzb_get_precision_value(val varchar(100),v_cash_acct_id varchar(10)) returns varchar(100) 
begin
  declare  ret_val varchar(100);
  declare v_index_precision integer ;
  declare v_calc_type varchar(1);
  if val is null or v_cash_acct_id is null then
  set ret_val=coalesce(val, '0');
    return ret_val;
  else
  select max(prc.index_precision), max(prc.calc_type)
    into v_index_precision, v_calc_type
    from v_gzb_index_precision prc
    inner join ttrd_wmps_define wps
      on prc.i_code = wps.i_code
     and prc.a_type = wps.a_type
     and prc.m_type = wps.m_type
    inner join ttrd_acc_cash acc_cash
    on wps.unit_id = acc_cash.pc1
   where wps.zmcp_flag = '0'
     and instr(wps.i_code, 'temp') = 0
     and prc.f_code = 'nav_other'
     and acc_cash.accid = v_cash_acct_id;
  end if;
   if coalesce(v_calc_type, '1') = '1' then
      set ret_val = left(val, instr(val,'.')+coalesce(v_index_precision, 8));
   else
    set ret_val = round(val, coalesce(v_index_precision, 8));
   end if;
    return ret_val;
-- 结束时使用指定的分隔符    
end $
--  最后修改分割符为默认值
delimiter ;

procedure 存储过程操作

drop procedure if exists tryaddtabcolumn;

delimiter $
create procedure `tryaddtabcolumn`(in tablename varchar(100),in colname varchar(50),in coltype varchar(1000))
begin
    declare colcount int;
    select count(*) into colcount from information_schema.columns where table_name = tablename and column_name = colname;
    if(colcount = 0) then
  -- @表示全局变量 相当于php $ 拼接赋值 into 必须要用全局变量不然语句会报错
  set @add_sql = concat('alter table ',tablename,' add column ',colname,' ',coltype,';');
  -- 预处理需要执行的动态sql,其中stmt是一个变量
  prepare stmt from @add_sql;
  -- 执行sql语句
  execute stmt;
  -- 释放掉预处理段
  deallocate prepare stmt;
end if;
end $
delimiter ;

附录

  • tryaddtable存储过程
drop procedure
    if
    exists tryaddtable;

delimiter $
create procedure `tryaddtable`(in tablename varchar(50),in createtablesql varchar(3000))
begin
    declare tablecount int;
    select count(*) into tablecount from information_schema.tables where table_name = tablename;
    if(tablecount = 0) then
	  -- @表示全局变量 相当于php $ 拼接赋值 into 必须要用全局变量不然语句会报错
    set @create_sql = createtablesql;
    -- 预处理需要执行的动态sql,其中stmt是一个变量
    prepare stmt from @create_sql;
    -- 执行sql语句
    execute stmt;
    -- 释放掉预处理段
    deallocate prepare stmt;
end if;
end $
delimiter ;
  • tryaddtabcolumn存储过程
drop procedure
    if
    exists tryaddtabcolumn;

delimiter $
create procedure `tryaddtabcolumn`(in tablename varchar(100),in colname varchar(50),in coltype varchar(1000))
begin
    declare colcount int;
    select count(*) into colcount from information_schema.columns where table_name = tablename and column_name = colname;
    if(colcount = 0) then
  -- @表示全局变量 相当于php $ 拼接赋值 into 必须要用全局变量不然语句会报错
  set @add_sql = concat('alter table ',tablename,' add column ',colname,' ',coltype,';');
  -- 预处理需要执行的动态sql,其中stmt是一个变量
  prepare stmt from @add_sql;
  -- 执行sql语句
  execute stmt;
  -- 释放掉预处理段
  deallocate prepare stmt;
end if;
end $
delimiter ;
  • trydropindex存储过程
drop procedure
    if
    exists trydropindex;

delimiter $
create procedure `trydropindex`(in tablename varchar ( 2000 ), in indexname varchar ( 2000 ))
begin
    declare row1 int;
    select
    count( * ) into row1
    from
    information_schema.statistics
    where
    table_schema = (select database())
    and table_name = tablename
    and index_name = indexname;
    if
    ( row1 > 0 ) then
    set @exeutesql = concat( 'alter table ', tablename, ' drop index ', indexname );
    prepare stmt from @exeutesql;
    execute stmt;
    deallocate prepare stmt;
end if;
end $
delimiter ;
  • trychangetabcolumn存储过程
drop procedure if exists trychangetabcolumn;

delimiter //
create procedure trychangetabcolumn (in tablename varchar(50),in origicolname varchar(50),in targetcolname varchar(50),in targetcoltype varchar(100))
begin
	declare colcount int;
  select count(*) into colcount from information_schema.columns where table_name = tablename and column_name = targetcolname;
	if(colcount > 0) then
		set @excute_sql = concat('alter table ',tablename,' modify column ',targetcolname,' ',targetcoltype,';');
	else
		set @excute_sql = concat('alter table ',tablename,' change ',origicolname,' ',targetcolname,' ',targetcoltype,';');
	end if;
	-- 预处理需要执行的动态sql,其中stmt是一个变量
	prepare stmt from @excute_sql;
	-- 执行sql语句
	execute stmt;
	-- 释放掉预处理段
	deallocate prepare stmt;
end //
delimiter ;

总结

到此这篇关于mysql常见的脚本语句格式南的文章就介绍到这了,更多相关mysql脚本语句格式内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!