2012-06-19 40 views
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')作爲一個字符串。我需要它將字符串視爲多個數據庫。

任何想法?

+0

對不起,我想澄清一點:您打算使用一些參數來設置要查詢的數據庫列表,右鍵? – raina77ow

+0

是的,這是正確的。 select into ignore_db的結果將是'db1','db2','db3'等字符串。我需要MySQL來字面處理字符串。 – dwjv

回答

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> 

BTW我環繞ignore_db額外的逗號的原因有做的數據庫名稱本身

如果您的數據庫具有通用前綴,則可能會出現您不打算的重複數據庫。例如,如果您有db1,db11,db2,db22,db111數據庫時,ignore_db爲db1,db2,則所有5個數據庫都將顯示爲結果。因此,我在WHERE子句中爲ignore_db和schema_name添加了額外的逗號

+0

啊,當然。真的很簡單。我正在從盒子裏面看問題。 非常感謝! – dwjv