0

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!

3
  • 2
    Don't inject your value, parametrise your query; then your value will be passed as a date/time datatype and will be parsed correctly. Commented Jul 3, 2019 at 10:58
  • 2
    Because you set local hours and the timestamp is UTC, presumably your system is set for +0200. Try datoen.setUTCHours(2,0,0,0). ;-) Commented Jul 3, 2019 at 11:00
  • Is it that "simple" @Larnu? I was going to figure out how to parametrise - as soon as I had the basic queries down :-) I guess I'll have to jump right into that then. Thanks a lot! Commented Jul 3, 2019 at 11:03

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Yep, Terry Lennox - that pretty much did the trick :-) Thanks a million!
Great, glad to hear it!!

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.