0

我是 DB2 查询的新手。

在这里,我在存储过程中将逗号分隔值作为 IN 参数传递。我想根据这些值进行搜索。

Select * from USER where user_id in (IN_User);

在这里,IN_User 将具有 ('val1','val2','val3') 类型的值

它应该返回所有具有 val1 或 val2 或 val3 作为 User_id 的行。据我所知,这可以使用 UDF 完成,但我想知道是否有其他方法可以在没有 UDF 的情况下做到这一点。

4

1 回答 1

2

请创建一个函数来拆分逗号分隔的字符串

请看下面的函数

CREATE FUNCTION StringToRows(
   cString1 CLOB (10 M) ,
   cStringSplitting1 VARCHAR(10) )
RETURNS TABLE (Lines VARCHAR(500))
SPECIFIC StringToRows_Big
DETERMINISTIC
NO EXTERNAL ACTION
CONTAINS SQL
BEGIN ATOMIC
 DECLARE cStringSplitting VARCHAR(10);
 DECLARE LenSplit SMALLINT;
 SET cStringSplitting = cStringSplitting1;
 SET LenSplit = LENGTH(cStringSplitting);

 IF LENGTH(TRIM(cStringSplitting)) = 0 THEN
  SET cStringSplitting = ' ', LenSplit = 1 ;
 END IF ;

RETURN WITH
   TEMP1 ( STRING) as (values (cString1) ),
   TEMP2 ( Lines, STRING_left) as
   (SELECT  
   SUBSTR(STRING,1, CASE WHEN LOCATE(cStringSplitting, STRING) = 0 THEN LENGTH(STRING) ELSE LOCATE(cStringSplitting,STRING) - 1 END),
   (CASE WHEN (LOCATE(cStringSplitting, STRING) = 0) THEN '' ELSE  SUBSTR(STRING, LOCATE(cStringSplitting,STRING) + LenSplit)  END)
   FROM TEMP1 WHERE LENGTH(STRING) > 0
   UNION ALL
     SELECT 
     SUBSTR(STRING_left,1, CASE LOCATE(cStringSplitting,STRING_left) WHEN 0 THEN LENGTH(STRING_left) ELSE LOCATE(cStringSplitting,STRING_left) - 1 END),
     (CASE WHEN LOCATE(cStringSplitting,STRING_left) = 0 THEN '' ELSE SUBSTR(STRING_left,  LOCATE(cStringSplitting,STRING_left) + LenSplit) END)
     FROM TEMP2 WHERE LENGTH(STRING_left) > 0 )
  SELECT Lines FROM TEMP2;
END  

请参阅示例存储过程以调用该函数

CREATE PROCEDURE  TEST_USR(IN @inputParam CLOB (10 M))
SPECIFIC TEST_USR
DYNAMIC RESULT SETS 1
P1: BEGIN
   DECLARE CURSOR1 CURSOR WITH RETURN FOR
             Select * from USER where user_id IN (SELECT * FROM TABLE(StringToRows(@inputParam, ',')) AS test);
   OPEN CURSOR1;
END P1 
于 2013-07-23T09:58:56.890 回答