tidb缺主键,补齐主键迁移TDSQL模版

create table  uni_eco_prod.sys_user_tag_new
(
	id           bigint auto_increment comment '主键'
		primary key,
	user_id bigint null comment '用户ID',
	tag_id  bigint null comment '标签ID'
)
	collate = utf8_unicode_ci;

-- 配置
SET @Scheme='uni_eco_prod';
SET @tableName = 'sys_user_tag';
SET @insertSQL = NULL;
-- 往临时表插入数据
SELECT @insertSQL := concat('INSERT INTO ',@Scheme,'.',@tableName,'_new (', GROUP_CONCAT(concat('`',column_name,'`') SEPARATOR ', '),') select ',GROUP_CONCAT(concat('`',column_name,'`') SEPARATOR ', '),' from ',@Scheme,'.',@tableName,';') AS column_list
FROM information_schema.columns
WHERE table_schema = @Scheme
  AND table_name = @tableName;


PREPARE stmt FROM @insertSQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- 改名
SET @RenameSql = CONCAT(
	'RENAME TABLE ', @Scheme, '.', @tableName, ' TO ', @Scheme, '.', @tableName, '_old, ',
	'', @Scheme, '.', @tableName, '_new TO ', @Scheme, '.', @tableName, '; '
);
-- 执行动态SQL
PREPARE stmt FROM @RenameSql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 删表
SET @DelSql = CONCAT(
	'DROP TABLE ',@Scheme, '.',@tableName, '_old;'
);
-- 执行动态SQL
PREPARE stmt FROM @DelSql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

  

posted @ 2026-10-29 11:45  蓝色土耳其  阅读(6)  评论(0)    收藏  举报