0

In my Node batch-processor project I am using the mssql package, and I need to gather data from two different SQL databases and then basically emulate a merge operation. My question is, for SQL Server, is there a way I can use IN to pass in an array of IDs as part of the inner SELECT?

To clarify, the IDs I'll be passing in have been gathered from a separate query from a different SQL database. So what I need to do now is pass those IDs into this next query.

I've seen this kind of syntax:

SELECT DISTINCT Name
FROM Production.Product
WHERE ProductModelID IN
    (SELECT ProductModelID 
     FROM Production.ProductModel AS pm
     WHERE p.ProductModelID = pm.ProductModelID
        AND Name LIKE 'Long-Sleeve Logo Jersey%');
GO

What would it look like to pass in those IDs as part of the inner SELECT statement? Is this something that can be done? Or is there a different way I should approach this?

And to clarify, I do need to do this within my Node project - so calling a stored procedure and using linked tables from my SQL Server database is not an option.

By the way, I could do something like this:

  getMatchingIdRecords = async function() {
    for (let sourceRecord of sourceArr) {
      const matchingIdRecord = await sqlServerQueryHandler(`SELECT NoteDetailsId FROM SR_Empsheets
      WHERE NoteDetailsId = ${sourceRecord.notes_detail_id}`);
      if (matchingIdRecord) matchingIdRecords.push(matchingIdRecord);
    }
    return matchingIdRecords;
  };

But this is less than ideal because I'm basically hitting the database for every record that is iterated through.

1 Answer 1

1

For SQL Server 2016+ you can pass a JSON Array to the query and parse it on the server. Something like:

SELECT NoteDetailsId FROM SR_Empsheets
      WHERE NoteDetailsId in ( select value from openjson(@jsonArray) )

Where @jsonArray is a nvarchar(max) parameter that looks like

 N'["1323","2311","1234"]'
Sign up to request clarification or add additional context in comments.

1 Comment

Good to know! I will double-check what version we're on and will try this. Thanks, @David.

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.