2

I want to select from a table where a field is in a given csv string passed to a stored proc.

What is the fastest way to do this? Should I insert the values into a temporary table and join to that? Or is there a way to do it with one statement?

Thanks

2 Answers 2

4

Did some searching around and found a great answer.:)

Use MySql's string function FIND_IN_SET.

Example use:

SET @csvStr = "val1,val2,val3";

SELECT Col1
  FROM Table1
 WHERE FIND_IN_SET(Col2, @csvStr) > 0;

I edited the current answer with the "New Answer" and "Old Answer" pointing out that the new answer opens up your system to a SQL Injection vulnerability.

Sign up to request clarification or add additional context in comments.

Comments

1

NEW ANSWER -

Well you have to do something like this as given below. I am assuming your csv string would be as given in variable @str below. Else you need to make sure that your string (or arraystring) should have this format with single quotes for every element -

set @str = "'some1','some2','some3'";
set @qry1 = CONCAT('select * from testing where col1 in (',@str,')');

prepare stmt1 from @qry1;
execute stmt1;
deallocate prepare stmt1; 

OLD ANSWER -

I assume that you will pass the csv file path to stored proc and read the lines in csv in that stored proc. So basically you can store all those csv field values in a temp table and write query using IN -

select * from sourceTable 
where fieldValue in (select csvFieldValue from #temptable)

4 Comments

No, it's not a file, just a text field like "token1,token2,token3" etc that is passed as the parameter.
@Chris - Edited my answer. Tested with given string and it works fine. You might have to do some manipulation of string array you have.
Have to do some manipulation of the string in the agent to get the quotes right, but works well, Thanks!
note that you cannot use dynamic sql in triggers, so this solution could not be used there

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.