简体   繁体   中英

convert to datetime not working sql query

i have this:

let startDateRange = loadYear + '-' + loadMonth + '-01'
let endDateRange = loadYear + '-' + loadMonth + '-31'
var getschedule = "select * from SCHEDULE where DATE BETWEEN '" + CONVERT(DATETIME, startDateRange) + "' AND '" + CONVERT(DATETIME, endDateRange) + "'"

and in startDateRange and endDateRange , it is formatted in a string like so:

'2021-Dec-01'

It is giving the error:

ReferenceError: CONVERT is not defined

how can i fix this?

You're missing some fundamentals here, I think.

var getschedule = "select * from SCHEDULE where DATE BETWEEN '" + CONVERT(DATETIME, startDateRange) + "' AND '" + CONVERT(DATETIME, endDateRange) + "'"`

Javascript thinks CONVERT is a function that you've defined in your Javascript code rather than a SQL command. Though you didn't provide a ton of context, what you're probably trying to do is construct a complete SQL query. If you want to interpolate the values you've calculated in your Javascript to this query you're going to give to your SQL database, you need to construct a complete string.

It might be easier (or more readable) to use template literals :

const getschedule = `select * from SCHEDULE where DATE BETWEEN 'CONVERT(DATETIME, ${startDateRange})' AND 'CONVERT(DATETIME, ${endDateRange})'`

Or you can concatenate strings as you tried the first time:

const getschedule = "select * from SCHEDULE where DATE BETWEEN 'CONVERT(DATETIME, " + startDateRange + ")' AND 'CONVERT(DATETIME, " + endDateRange + ")'";

Full disclosure: I have no idea whether or not this SQL query will be valid for you, it's just clear that you're thinking the wrong way about Javascript functions and how to construct strings.

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