简体   繁体   中英

Date time varchar conversion

I've looked through other answers. For some reason they don't seem to fix my problem. This is the sql code:

SELECT *
FROM invoices
WHERE InvoiceDate BETWEEN CONVERT(datetime,'2012-00-00',120) AND CONVERT(datetime,'2013-00-00',120  )
ORDER BY InvoiceDate DESC

I keep getting the following error message: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

SELECT *
FROM invoices
WHERE InvoiceDate >= '2012-01-01' AND InvoiceDate < '2013-01-01'
ORDER BY InvoiceDate DESC

You have the following: CONVERT(datetime,'2012-00-00',120). You can't make a date that doesn't have a day or month.

Using a named parameter:

DECLARE @year INT;
SET @year = 2012;
SELECT *
FROM invoices
WHERE InvoiceDate >= DateFromParts(@year,1,1) AND InvoiceDate < DateFromParts(@year+1,1,1)
ORDER BY InvoiceDate DESC;

If DateFromParts is not availanbe (pre-2012 MSSQL) the date can be created like this

WHERE InvoiceDate >= DateAdd(Year,@year-1900,0) AND InvoiceDate < DateAdd(Year,@year-1899,0)

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