使用SQL语句更改忽略表添加列(如果不存在) [英] Alter ignore table add column if not exists using the SQL statement

查看:662
本文介绍了使用SQL语句更改忽略表添加列(如果不存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向mysql表中添加新列,但是如果该列已存在,我想忽略该列的添加

i want to add a new column to a mysql table, but i want to ignore the adding of column, if the column already exists

我当前正在使用

ALTER IGNORE TABLE `db`.`tablename` ADD COLUMN `column_name` text NULL;

但这会引发错误:"ERROR 1060 (42S21): Duplicate column name 'column_name'"

即使我使用的是IGNORE,也无法正常工作

even though i am using the IGNORE, this is not working

我希望它能使用普通的SQL语句而不是存储过程来工作

i want this to work using the normal SQL statement, instead of a stored procedure

推荐答案

根据文档:

IGNORE是对标准SQL的MySQL扩展.它控制着如何改变 如果新表中的唯一键上有重复项,则TABLE起作用 如果在启用严格模式时发生警告.如果不是IGNORE 指定,如果重复键错误,副本将中止并回滚 发生.如果指定了IGNORE,则只有一行用于 在唯一键上重复.其他冲突的行将被删除. 不正确的值将被截断为最接近可接受的匹配值 值.

IGNORE is a MySQL extension to standard SQL. It controls how ALTER TABLE works if there are duplicates on unique keys in the new table or if warnings occur when strict mode is enabled. If IGNORE is not specified, the copy is aborted and rolled back if duplicate-key errors occur. If IGNORE is specified, only one row is used of rows with duplicates on a unique key. The other conflicting rows are deleted. Incorrect values are truncated to the closest matching acceptable value.

也就是说,它用于不同的目的,而不是所有的错误.您想要的是类似ALTER TABLE ADD IF NOT EXISTS的东西,并且该语法不存在.

That is, it is used for a different purpose, not all errors. What you want is something like ALTER TABLE ADD IF NOT EXISTS, and that syntax doesn't exist.

在存储过程中,可以使用if语句查看该列是否已经存在(使用INFORMATION_SCHEMA.COLUMNS).

In a stored procedure, you can use an if statement to see if the column already exists (using INFORMATION_SCHEMA.COLUMNS).

此处是显示相同问题的SQL提琴.

Here is a SQL Fiddle that shows the same problem.

这篇关于使用SQL语句更改忽略表添加列(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆