Search code examples
node.jssql-servernode-mssql

How to pass date as an input to SQL Server query in node


I am using node-mssql and my function goes like this:

const getPoliciesDue = async (userId, toDate) => {
  const db = await sql.connect(config) // const sql = require('mssql'), config = {config for my DB}
  const request = db.request()
    .input('userId', sql.VarChar, userId) // userId is a string
    .input('toDate', sql.Date, toDate) // toDate is a javascript Date() object
  const result = await request.query(
  'SELECT policyNumber, holderId, ... FROM Policies WHERE Policies.userId = @userId AND Policies.toDate <= @toDate'
  )
  return result.recordset
}

I want to get all the policies which are expiring before a certain date belonging to a certain user.

But when I run this exact query, I get the error

Must declare the scalar variable @userId

I removed @userId from the WHERE clause and put '@toDate' (quotes around the variable). Now I get an error

Conversion failed when converting date and/or time from character string

The documentation says input() accepts the Date() object. I have tried passing date object as well as a string in YYYY-MM-DD format, but with no avail. Passing a string in YYYY-MM-DD format works for an INSERT query, but not for a SELECT query. How am I supposed to run my query?

Note I can't run the query in a single line, like

db.request().input().query()

because there is another input which will later go in conditionally.


Solution

  • Okay, a huge oversight on my part and sincere apologies to those who tried to find an answer. I found out that I was running the query() method on the wrong object. I was running the query method on db object whereas I should have run it on the request object. The code works perfectly after calling the method on the right object.