我正在尝试使用逗号分隔的字符串作为存储过程中查询的一部分但无法使其工作。我希望字符串为:
'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')
视为一个字符串。我需要它将字符串视为多个数据库。
有什么想法吗?
答案 0 :(得分: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的原因与数据库名称本身有关
如果您的数据库具有公共前缀,则可能会出现您不想要的重复数据库。例如,如果在数据库db1,db11,db2,db22,db111中,ignore_db为db1,db2,那么所有5个atabases都将显示为结果。因此,我在WHERE子句
中为ignore_db和schema_name添加了额外的逗号