Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

db2 - Passing comma separated value as an IN parameter in stored procedure

I am new to DB2 queries.

Here, I am passing a comma separated value as an IN parameter in a Stored Procedure. I want to search on the basis of those values.

Select * from USER where user_id in (IN_User);

Here, IN_User will have values of the kind ('val1','val2','val3')

It should return all the rows which has val1 or val2 or val3 as the User_id. As much as I know this can be done using UDF but I want to know is there any other way to do it without UDF.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

please create a function to split the comma separated string

Please see the below function

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  

please see the sample stored procedure to call the function

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...