0

I am using the mssql package in my Node project to handle querying for data in my SQL Server db. I am running into a challenge with this particular query:

const idArr = ['A123', 'B456'];

SELECT DOCNO
FROM dbo.SA30301
WHERE DOCNO
IN (${idArr})

The problem is that, with this syntax, the values will not be passed in as strings, even though the array contains string values. So with this implementation I get an invalid column name error.

I've also tried this:

SELECT DOCNO
FROM dbo.SA30301
WHERE DOCNO
IN ('${idArr}')

... and while this doesn't error out, it doesn't return any records because basically both values are passed in as one long string.

Also, FYI, the type for DOCNO in SQL Server is char(17).

So my question is, how can I make sure these values get evaluated as individual string values?

My other option may be to use a for-loop and go one by one, but that will result in many hits to the db rather than just one.

1 Answer 1

1

Try with a Javascript's join function

SELECT DOCNO
FROM dbo.SA30301
WHERE DOCNO
IN (${idArr.map(item => `'${item}'`).join(',')})

You may need to escape the quotes.

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

3 Comments

And I would recommend editing your question with an example of what you mean by "individual strings"
I've edited my answer. The quotes before and after every item will make it so that you will get "A123","B456"
Nice one! I made one small edit to your answer, because in SQL Server those need to be single quotes, not double. But other than that this works perfectly!

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.