如何将日期作为输入传递给节点中的 SQL 服务器查询

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

我正在使用 node-mssql,我的功能是这样的:

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
}

我想获取属于特定用户的特定日期之前到期的所有保单。

但是当我 运行 这个确切的查询时,我得到了错误

Must declare the scalar variable @userId

我从 WHERE 子句中删除了 @userId 并放置了 '@toDate'(变量两边的引号)。现在我得到一个错误

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

The documentation 表示 input() 接受 Date() 对象。我试过传递日期对象以及 YYYY-MM-DD 格式的字符串,但无济于事。传递 YYYY-MM-DD 格式的字符串适用于 INSERT 查询,但不适用于 SELECT 查询。我应该如何 运行 我的查询?

注意我不能运行单行查询,比如

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

因为还有另一个输入,稍后将有条件地输入。

好的,这是我的一个巨大疏忽,并对那些试图找到答案的人表示诚挚的歉意。我发现我在错误的对象上 运行ning 了 query() 方法。我在 db 对象上 运行ning 查询方法,而我应该在 request 对象上 运行 它。在正确的对象上调用方法后,代码完美运行。