简体   繁体   中英

Using dates when querying MSSQL from node.js

I'm trying to query MSSQL from node.js and the query involves dates.

I set my query-date like this:

var datoen = new Date();
datoen.setHours(2,0,0,0);

First of all - on my server this logs out as: 2019-07-03T00:00:00.000Z

Why does it not log out as: 2019-07-03T02:00:00.000Z?

Anyway - that's not really the question. It's the first date format I want and it is identical to the format in the database.

But when I run this query (using mssql from npm):

request.query('select * from tblPriceRooms where 
BarDate = ' + datoen, function (err, recordset) {
        if (err) console.log(err)
        res.send(recordset)

... the server provides this error -->

     info:
  { number: 102,
    state: 1,
    class: 15,
    message: 'Incorrect syntax near \'Jul\'.',
    serverName: 'SERVERNAME\\SQLEXPRESS',
    procName: '',
    lineNumber: 1,
    name: 'ERROR',
    event: 'errorMessage' } },
    name: 'RequestError',
    precedingErrors: [] }

I know the connection works fine. As long as I do not try to query based on dates - I get all the results in the world.

I'm a novice and dates do my head in some times. Any pointers would be highly appreciated!

I'd suggest using parameters for the query, you get a lot of benefits from this approach. This should work for you:

// Put whatever date you wish here..
const date = new Date();
date.setUTCHours(2, 0, 0, 0);
request.query('select * from tblPriceRooms where BarDate > @date', (err, result) => {
    if (err) {
        console.error("Error occurred: ", err);
    } else {
        console.info("Rows: ", result);
    }
}).input('date', sql.DateTime, date); // Add the date parameter here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM