mysql提取建表语句_获取MySQL中某个数据库下所有表建表
语句的DDL
本脚本可以获取MySQL中某个数据库下所有表建表语句的DDL
注意:本脚本需在MySQL8.0以上版本运⾏
注意:本脚本不获取VIEW创建语句
注意:本脚本没有处理主键,外键等约束
注意:本脚本只处理⾮分区表,分区表请⾃⼰改写脚本
注意:如果你做数据迁移,想把MySQL数据库迁移到其他数据库,⾃⼰改写脚本
WITH tab AS
(SELECT table_name FROM information_schema.TABLES WHERE table_schema = '数据库名' and table_type='BASE TABLE') SELECT CASE
WHEN id = -1 THEN
concat('create table ', table_name)
WHEN id = 0 THEN
'('
WHEN id = 1 AND max_id = 1 THEN
concat(' ', column_name, ' ', column_type)
WHEN id = 1 AND max_id <> 1 THEN
concat(' ', column_name, ' ', column_type, ',')
WHEN id >= 1 AND id < max_id THEN
concat(' ', column_name, ' ', column_type, ',')
WHEN id = max_id THEN
concat(' ', column_name, ' ', column_type)
mysql视图和存储过程
WHEN id = 999 THEN
');'
END create_table_ddl
FROM (SELECT table_name,
ordinal_position id,
max(ordinal_position) over(PARTITION BY table_schema, table_name) max_id,
column_name,
concat(column_type,
CASE
WHEN is_nullable = 'NO' THEN
' not null'
ELSE
''
END,
CASE
WHEN COLUMN_DEFAULT IS NULL THEN
''
WHEN COLUMN_DEFAULT IS NOT NULL AND
data_type IN ('varchar', 'char') THEN
concat(' default ', '''', column_default, '''')
WHEN COLUMN_DEFAULT IS NOT NULL AND
data_type NOT IN ('varchar', 'char') THEN
concat(' default ', column_default)
END,
'',
REPLACE(REPLACE(extra, 'DEFAULT_GENERATED', ''),
'auto_increment',
'')) column_type
FROM information_schema.COLUMNS
WHERE table_schema = '数据库名' and table_name in (select table_name from tab)
UNION ALL
SELECT table_name, -1 ordinal_position, NULL, NULL, NULL
FROM tab
UNION ALL
SELECT table_name, 0 ordinal_position, NULL, NULL, NULL
FROM tab
UNION ALL
SELECT table_name, 999 ordinal_position, NULL, NULL, NULL
FROM tab
ORDER BY table_name, id) a;
抓出当前账户下主键,外键,索引,视图,注释,check约束,函数,存储过程等等我就不贴了
想精通SQL优化?精通SQL? 精通系统优化?精通表设计?精通分库分表? 加我 692162374 报个名学习吧

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。