5

Possible Duplicates:
Parameterizing a SQL IN clause?
SQL Server - In clause with a declared variable

Hi,

I am facing problem passing parameters to 'IN' clause. I am using the below query.

Query:

SELECT Topics.Topic_Id  FROM Topics 
    Where Topic_Description IN (''+ @Topics +'')    

This query works when the parameter has single value. My parameter can have comma separated multiple values like : 'one','two','three','four'. But the query fails whenever there are multiple parameters. How to get over this ? Please suggest.

Thanks

I have to use the above as part of a stored procedure. I have to take the result of the select query into a cursor like below:

DECLARE cur_TopicIDs CURSOR FOR SELECT Topics.Topic_Id FROM Topics Where Topic_Description IN (''+ @Topics +'')....etc

In this case how can I use dynamic sp as suggested in other links

0

2 Answers 2

3

Use any of the split functions from here: http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648

1
0

You have to create a string of format one','two','three as value in the @Topics.

EDIT:- Then you need to use EXEC sp_executesql to execute your sql statement. The answer is properly explained in the link given by spender for your question.

7
  • You're sure about this? OP doesn't make it clear where the query is being assembled.
    – spender
    Jan 18, 2011 at 10:44
  • @spender - I have not tried this myself. But since its a string substitution, I suppose this will work. becacuse OP is already adding the first ' and last '. In between we need to fill it with a string of given format. Jan 18, 2011 at 10:46
  • This approach would be vulnerable to SQL injection. The split function is safer. Jan 18, 2011 at 10:48
  • @Martin - Aah.. yes. I think you are right. I did not think about SQL Injection. Jan 18, 2011 at 10:49
  • I am creating a string of format one','two','three as value but it is still not working
    – San
    Jan 18, 2011 at 10:50

Not the answer you're looking for? Browse other questions tagged or ask your own question.