MySql 批量添加主键,设置自增属性
spooking 归属分类: 开发运维 评论数: 0 个

批量设置主键(默认表格的第一个字段)

SELECT CONCAT(
    'ALTER TABLE ', TABLE_NAME,
    ' ADD PRIMARY KEY (', COLUMN_NAME, ');'
) AS sql_statement
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '数据库名字'
    AND ORDINAL_POSITION = 1
    AND COLUMN_KEY <> 'PRI';

批量添加自增(默认表格的第一个字段)

SELECT CONCAT(
    'ALTER TABLE ', TABLE_NAME,
    ' MODIFY COLUMN ', COLUMN_NAME, ' ', COLUMN_TYPE,
    ' AUTO_INCREMENT;'
) AS sql_statement
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = '数据库名字'
    AND ORDINAL_POSITION = 1
    AND EXTRA NOT LIKE '%auto_increment%'
    AND COLUMN_TYPE IN ('int', 'bigint', 'mediumint', 'smallint', 'tinyint');