簡體   English   中英

如何在sql腳本而不是存儲過程中有選擇地執行某些sql語句

[英]How to selectively exec some sql statement in a sql script, not in a stored procedure

我正在編寫一個SQL腳本,其中應包含一些選擇邏輯,例如:

  if: we have some foreign key that referenced this table
  then: delete all of those.
  drop: this table

這一系列的SQL語句未包含在存儲過程中,因此無法使用if語句。

輸入:

use test;
create table test01 ( a integer, b char, c datetime );
create table test02 ( a char, b datetime, c integer );

“ MySQL需要外鍵和引用鍵上的索引...” 外鍵上的MySQL Doc

create index test02_idx1 on test02(c);
create index test01_idx1 on test01(a);
alter table test02 add foreign key ( c ) references test01(a);

use information_schema;
select 
  c.constraint_schema
 ,c.constraint_name 
 ,c.table_name
 ,c.referenced_table_name
 ,CONCAT('ALTER TABLE ',c.table_name,' DROP FOREIGN KEY ',c.constraint_name,'; DROP TABLE ',c.referenced_table_name,';') as command
from
  key_column_usage c
  ,table_constraints t 
where 
  c.constraint_name = t.constraint_name 
  and c.referenced_table_name = 'test01';

+-------------------+-----------------+------------+-----------------------+-----------------------------------------------------------------------+
| constraint_schema | constraint_name | table_name | referenced_table_name | command                                                               |
+-------------------+-----------------+------------+-----------------------+-----------------------------------------------------------------------+
| test              | test02_ibfk_1   | test02     | test01                | ALTER TABLE test02 DROP FOREIGN KEY test02_ibfk_1; DROP TABLE test01; |
+-------------------+-----------------+------------+-----------------------+-----------------------------------------------------------------------+
1 row in set (0.23 sec)

因為您有一系列語句不包含在存儲過程中,所以需要確保三件事:

  • 打印命令( select 'drop foreign key; drop table;';
  • 禁用邊框和列的標題( -B --disable-column-names
  • 將輸出打印到文件( > output.sqltee

mysql -B -u user -p --disable-column-names < script.sql

您需要將輸出寫入文件。 有兩種方法:

1.一次執行

mysql -B -u user -p --disable-column-names < script.sql > output.sql

select 
 CONCAT('ALTER TABLE ',c.table_name,' DROP FOREIGN KEY ',c.constraint_name,'; DROP TABLE ',c.referenced_table_name,';') as command
from
  key_column_usage c
  ,table_constraints t 
where 
  c.constraint_name = t.constraint_name 
  and c.referenced_table_name = 'test01';
source output.sql
quit;

2.兩次處決

...或在script.sql內部:

tee output.sql
select 
 CONCAT('ALTER TABLE ',c.table_name,' DROP FOREIGN KEY ',c.constraint_name,'; DROP TABLE ',c.referenced_table_name,';') as command
from
  key_column_usage c
  ,table_constraints t 
where 
  c.constraint_name = t.constraint_name 
  and c.referenced_table_name = 'test01';
notee
quit;

然后

mysql -u user -p < output.sql

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM