0

我正在尝试使用逗号分隔的字符串作为存储过程中查询的一部分,但无法使其正常工作。我希望字符串是:

'db1', 'db2','db3'

这是该过程的一个示例(为了便于阅读,我省略了很多代码):

CREATE PROCEDURE test(taskId int)
begin

declare done int default false;
declare ignore_db varchar(1024);

declare cur1 cursor for select schema_name from information_schema.schemata where schema_name not in (ignore_db);
declare continue handler for not found set done = true;

select value into ignore_db from dbw_parameters where upper(name)=upper('ignore db') and task_id = taskID;

select schema_name from information_schema.schemata where schema_name not in (ignore_db);
end;

我试过了:

set ignore_db=concat('\'',replace(ignore_db,',','\',\''),'\'');

但它只是将结果('db1','db2','db3')视为一个字符串。我需要它将字符串视为多个数据库。

有任何想法吗?

4

1 回答 1

1

您无需在列表中添加引号。只需使用LOCATE功能

CREATE PROCEDURE test(taskId int)
begin

declare done int default false;
declare ignore_db varchar(1024);

declare cur1 cursor for select schema_name from information_schema.schemata where schema_name not in (ignore_db);
declare continue handler for not found set done = true;

select value into ignore_db from dbw_parameters where upper(name)=upper('ignore db') and task_id = taskID;

select schema_name from information_schema.schemata
where LOCATE(CONCAT(',',schema_name,','),CONCAT(',',ignore_db,',')) > 0;

end;

这是以这种方式使用 LOCATE 函数的原始示例:

mysql> select LOCATE(',db1,',',db1,db2,db3,');
+---------------------------------+
| LOCATE(',db1,',',db1,db2,db3,') |
+---------------------------------+
|                               1 |
+---------------------------------+
1 row in set (0.00 sec)

mysql> select LOCATE(',db2,',',db1,db2,db3,');
+---------------------------------+
| LOCATE(',db2,',',db1,db2,db3,') |
+---------------------------------+
|                               5 |
+---------------------------------+
1 row in set (0.00 sec)

mysql> select LOCATE(',db3,',',db1,db2,db3,');
+---------------------------------+
| LOCATE(',db3,',',db1,db2,db3,') |
+---------------------------------+
|                               9 |
+---------------------------------+
1 row in set (0.00 sec)

mysql> select LOCATE(',db4,',',db1,db2,db3,');
+---------------------------------+
| LOCATE(',db4,',',db1,db2,db3,') |
+---------------------------------+
|                               0 |
+---------------------------------+
1 row in set (0.00 sec)

mysql>

顺便说一句,我用附加逗号包围 ignore_db 的原因与数据库名称本身有关

如果您有具有公共前缀的数据库,则可能会出现您不希望出现的重复数据库。例如,如果 ignore_db 是 db1,db2 而您有数据库 db1,db11,db2,db22,db111,那么所有 5 个数据库都会作为结果出现。因此,我在 WHERE 子句中为 ignore_db 和 schema_name 添加了额外的逗号

于 2012-06-19T16:44:21.833 回答