0

I am trying to pass a comma separated values in a variable to the select statement but I am not getting the result.

Here is the SQL:

DECLARE @dataCodes XML = '<Root>
                    <List Value="120" />
                    <List Value="110" />
                </Root>';      

DECLARE @ConcatString VARCHAR(MAX);

SELECT @ConcatString = COALESCE(@ConcatString + ',','') + Code
FROM (
    SELECT T.Item.value('@Value[1]', 'VARCHAR(MAX)') AS Code
    FROM @dataCodes.nodes('/Root/List') AS T(Item)
    ) as TBL

SET @ConcatString=''''+REPLACE(@ConcatString,',',''',''') +'''';

SELECT NAME, ID, ROLE from MyTable where CODE in (@ConcatString); -- not working

Output of @ConcatString

enter image description here

Note:

If I pass the values directly as shown below, I am able to see the result,

SELECT NAME, ID, ROLE from MyTable where CODE in ('110','120');

I am trying this because, my SQL structure is something like:

 WITH JMATRIX_RESULT AS(      
       SELECT DISTINCT  ... from MyTable1 where CODE in (@ConcatString)
UNION
       SELECT DISTINCT  ... from MyTable2 where CODE in (@ConcatString)
UNION 
       SELECT DISTINCT  ... from MyTable3 where CODE in (@ConcatString)
),
...

and I see performance improvement when passing the parameter as comma separated values.

Expectation:

If I pass the dynamically created comma separated values in string (@ConcatString) to the in clause of select statement, it should return the values.

Any suggestion is appreciated.

3
  • what is the data type of code Commented Oct 1, 2015 at 17:44
  • datatype of code is VARCHAR Commented Oct 1, 2015 at 17:46
  • you have to create dynamic query then execute it Commented Oct 1, 2015 at 17:50

1 Answer 1

2

Why are you concatenating the string simply do the following :

DECLARE @dataCodes XML = '<Root>
                            <List Value="120" />
                            <List Value="110" />
                          </Root>'; 


SELECT NAME, ID, ROLE 
from MyTable 
where CODE in (
                SELECT T.Item.value('@Value[1]', 'VARCHAR(MAX)') AS Code
                FROM @dataCodes.nodes('/Root/List') AS T(Item)
               );
Sign up to request clarification or add additional context in comments.

2 Comments

My original code was like this but, I am having performance issue and I observed that replacing the current select statement within the 'in' clause with comma separated string increased the performance significantly. I have updated the question with my SQL Structure and I hope it gives the idea.
I am staying with the same code, which is the solution you have suggested.

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.