简体   繁体   English

MySQL存储过程更改多表结构

[英]Mysql stored procedure to alter mutiple tables structure

I'm building a small script as a function or a stored procedure to be able to alter a table structure only in tables that has no column named 'address'. 我正在构建一个小的脚本作为函数或存储过程,以便仅在没有名为“ address”的列的表中才能更改表结构。

If the table doesn't have the column address then the script will add it: 如果表没有列地址,那么脚本将添加它:

ALTER TABLE XXXX ADD COLUMN address VARCHAR(150) NULL after command;

So far I have found the way to access to the tables list that HAS the column 'address' on its structure by querying the information_schema.COLUMNS table; 到目前为止,我已经找到了访问表列表的方法,该方法是通过查询information_schema.COLUMNS表在其结构上具有列“地址”; such thing is not what I need because I need exactly the opposite, which is tables list that has not the column named 'address' on its structure. 这样的事情不是我所需要的,因为我需要的恰好相反,即表列表的结构上没有名为“ address”的列。

so basically is a script that needs to do something like this: 所以基本上是一个脚本,需要执行以下操作:

ALTER TABLE 
(SELECT TABLE_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'mydatabase' 
AND TABLE_NAME LIKE 'mytable_%' AND COLUMN_NAME = 'address') 
ADD COLUMN IF NOT EXISTS address  VARCHAR(150) NULL after command;

Something like that is what I need, it needs the validation of column name address and it will attempt to add the column only if it does not exists, otherwise it will return an exception and the query will die. 我需要的是这样的东西,它需要验证列名的地址,并且仅在不存在的情况下才会尝试添加该列,否则它将返回一个异常,并且查询将死亡。

PHP or any other programming language cannot be used because more than 4000 tables will be upgraded and the http request will die before the database finish the operations. 无法使用PHP或任何其他编程语言,因为将升级4000多个表,并且HTTP请求将在数据库完成操作之前终止。

Another possibility is to just handle the exception in case of the existence of the column named 'address' something to be able to continue the operations no matter if the exception returns, something that just continue with the query execution so the tables without exceptions will be updated.... 另一种可能性是在存在名为“ address”的列的情况下仅处理异常,以便无论异常返回如何都可以继续操作,该操作可以继续执行查询,因此没有异常的表将更新....

You will have to build dynamic SQL for this. 您将为此构建动态SQL。 The best bet is to do this 最好的选择就是这样做

OOTOMH code OOTOMH代码

Select 'Alter table ' + TableName ' + Add Address VarChar (150)'
From Information_schema.Tables T
Where Not Exists
(
Select 1
From Information_schema.Columns C
Where C.TableName = T.TableName
And C.ColumnName = 'Address'
)

Now that you have generated the code, you can execute it by hand. 现在您已经生成了代码,您可以手动执行它。

If this isn't really something you do on a daily basis, then there isn't much of a need to deploy the Stored Proc, is there? 如果这不是您每天真正要做的事情,那么就不需要太多部署Stored Proc了吗?

If you really really want it, then you have a plethora of options - add the string to a variable, loop through the set with a cursor, etc. 如果您真的很想要它,那么您有很多选择-将字符串添加到变量,使用游标在集合中循环等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM