0

对于每个表记录,我必须在第二个表中查找/检查该记录,并根据子字符串条件将结果放回一个字段中,如果多于一个,则用分隔符分隔。

table2->someRef 总是以两个 char + 其他东西开头,比如两个最多 14 的数字或一些字符串

函数 GetMeResult(param_ID) 正在工作,但使用游标非常慢

如果这可以通过一些连接或一些子查询或连接等来完成,那就太好了

示例表:

Table1 
------------------------
ID        Field1 Field2
-------------------------
100       text1  text2

Table2
=======================================
table2_ID, someCode, someRef
---------------------------------------
100        110       SB
100        222       SB1
100        150       SB14
100        200       PB9

Function GetMeResult(param_ID)
BEGIN
  DECLARE resultSomeCode VARCHAR(100);
  DECLARE tmpSomeCode VARCHAR(4);
  DECLARE delimeter VARCHAR(2);

  DECLARE tmpCur CURSOR FOR Stmt;

  set delimeter =', ';

  PREPARE Stmt FROM 'SELECT someCode FROM Table2 
  WHERE table2_ID=? and substring(table2.someRef, 3, 2) in   (''1'',''2'',''3'',''4'',''5'',''6'',''7'',''8'',''9'',''10'',''11'',''12'',''13'',''14'')'; 

     OPEN tmpCur USING param_ID;


      FETCH FIRST FROM tmpCur('someCode') INTO resultSomeCode ;
      WHILE NOT EOF(tmpCur) DO
         if length(tmpSomeCode)>0 then
           set resultSomeCode = resultSomeCode + delimeter + tmpSomeCode;
         end if;

         FETCH NEXT FROM tmpCur('someCode') INTO tmpSomeCode;
      END WHILE;

      CLOSE tmpCur;

      RETURN resultSomeCode;

END

用法:

SELECT ID, Field1, Field2, GetMeResult(ID) as SomeNameForField from Table1 

Result should be like 
======================
ID   Field1  Field2  SomeNameForField
-------------------------------------
100, text1,  text2,  '222, 150, 200' 

PS 字段和其他名称仅用于示例目的:)

谢谢

亲切的问候

4

0 回答 0