SQL Server error in conversion of date from string - sql

NPD.CreatedOn is defined as a datetime datatype column (in SQL Server).
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(MONTH, CONVERT(VARCHAR(7), NPD.CreatedOn, 126), CONVERT(VARCHAR(30), GETDATE(), 126)) <= 6
I get this error:
Conversion failed when converting date and/or time from character string.
What can I try to resolve it?

Don't use things like DATEDIFF in the WHERE on your columns, such queries aren't SARGable and thus can (will) perform poorly. If you want rows where the date is on or after the start of the month 6 months ago then do the date logic on GETDATE()/SYSDATETIME()/etc:
SQL Server doesn't have a "start of month" function, but you can use EOMONTH and then add a day:
SELECT *
FROM dbo.NPDMaster NPD
WHERE NPD.CreatedOn >= DATEADD(DAY, 1, EOMONTH(GETDATE(),-7));

You don't need to convert the datetime values to text. DATEDIFF() expects datetime values as second and third argument:
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(month, NPD.CreatedOn, GETDATE()) <= 6
The actual reason for the error (as is explained in the documentation), is that ...DATEDIFF implicitly casts string literals as a datetime2 type.

Related

Change a datetime2 column to date

I'm trying to convert a column in SQL Server Express from a datetime2(7) format to a date format.
I have tried convert, a number of different ways with brackets and parenthesis but I'm having issues either with 'binding' or syntax.
dbo.stateByStatehood.annexDate
USE bigCity
--1.
SELECT CONVERT(datetime2(7), GETDATE()) annexDate;
--2.
SELECT CONVERT (datetime2(7)), stateByStatehood.annexDate date
You can go for cast to date datatype as given below:
SELECT CONVERT(date, GETDATE()) as annexDate;
SELECT CAST(GETDATE() AS DATE) as annexDate
annexDate
2021-08-27

Convert Numeric to Date in MS SQL

There is already a Datecolumn in Table which is in Numeric DataType(Converted to Int for faster ODBC Transfer), How can i convert that number to Data again?
Example the Values are like
42508
42826
43191
42158
42527
Which are nothing but like
SELECT CONVERT(numeric, getdate())
Query Result
43571
Just want to know how can i convert back that to normal date ?
You may use next conversion:
SELECT CONVERT(date, DATEADD(day, 43570, 0))
which will output:
17/04/2019 00:00:00
In this case SQL Server will use implicit data type conversion, because DATEADD() allows datetime datatype as third parameter and DATEADD() will convert 0 to 1900-01-01.

Date Manipulation in SQL

I tried different functions to convert Datepart for year, month and day to a date but I am getting errors.
This is what I tried:
SELECT
CONVERT(datetime, CHAR(YEAR(GETDATE()) + CHAR(DATEPART(MM, '02')) + CHAR(DATEPART(DD, '28')));
When running this code, I get an error:
Conversion failed when converting date and/or time from character string.
In case I remove those single quotes on 02 and 28 then SQL will return null.
Thanks in advance
If 2012+ you could also try DateFromParts()
Select DateFromParts(2016,2,28)
Returns
2016-02-28
Try this instead:
SELECT CONVERT(datetime, DATENAME(YEAR, GETDATE()) + '-02-28')
You can't extract a day or month from a string such as '02'. But there is no need to do that anyway.
As you can read in the documentation on DATEPART, the second parameter should be a date parameter:
Returns an integer that represents the specified datepart of the specified date.
In your SQL statement you are misusing this function twice... following are invalid because the second parameter cannot be converted to a date type:
DATEPART(MM,'02')
DATEPART(DD,'28')
You can construct a date from its parts using the DATEFROMPARTS function in SQL Server 2012 and later versions:
Returns a date value for the specified year, month, and day.
Or if you need the time parts filled in as well, DATETIMEFROMPARTS
Returns a datetime value for the specified date and time.
In versions prior to SQL Server 2012, this can be done like this:
DATEADD(MM, (#year - 1900) * 12 + #month - 1 , #day - 1);

Subtract two dates in Microsoft SQL Server

I want to subtract 2 dates in MS SQL Server.
Example:
Current date Last used date
'2016-03-30' '2015-02-03'
Current date refers to today's date, "Last used date" is a measure.
How to write a query in SQL Server?
I have this but doesn't work (it says "Operand data type is invalid for subtract operator")
select
CONVERT(DATE, GETDATE()) - CONVERT(DATE, LastUsedDate)
from
databasename
SELECT DATEDIFF(day,'2014-06-05','2014-08-05') AS DiffDate
Output DiffDate 61
More practice please refer below W3 school:
https://www.w3schools.com/sql/func_sqlserver_datediff.asp
Here you don't have to cast GETDATE() to date, as it is already datetime datatype. So your query will be as follows
SELECT DATEDIFF(day,CAST(LastUsedDate as date),GETDATE()) AS DifferneceDays
FROM TableName
The normal function to use is datediff():
select datediff(day, cast('2016-02-03' as date), cast('2016-03-30' as date))
You can subtract datetime values, but not dates. Alas.

How do you extract just date from datetime in T-Sql?

I am running a select against a datetime column in SQL Server 2005. I can select only the date from this datetime column?
Best way is:
SELECT DATEADD(day, DATEDIFF(Day, 0, #ADate), 0)
This is because internally, SQL Server stores all dates as two integers, of which the first one is the ****number of days*** since 1 Jan 1900. (the second one is the time portion, stored as the number of seconds since Midnight. (seconds for SmallDateTimes, or milleseconds for DateTimes)
Using the above expression is better because it avoids all conversions, directly reading and accessing that first integer in a dates internal representation without having to perform any processing... the two zeroes in the above expression (which represent 1 Jan 1900), are also directly utilized w/o processing or conversion, because they match the SQL server internal representation of the date 1 jan 1900 exactly as presented (as an integer)..
*NOTE. Actually, the number of date boundaries (midnights) you have to cross to get from the one date to the other.
Yes, by using the convert function. For example:
select getdate(), convert(varchar(10),getdate(),120)
RESULTS:
----------------------- ----------
2010-05-21 13:43:23.117 2010-05-21
You can use the functions:
day(date)
month(date)
year(date)
Also the Datepart() function might be of some use:
http://msdn.microsoft.com/en-us/library/ms174420(SQL.90).aspx
DECLARE #dToday DATETIME
SET #dToday = CONVERT(nvarchar(20), GETDATE(), 101)
SELECT #dToday AS Today
This returns today's date at 12:00am : '2010-05-21 00:00:00.000'
Then you can use the #dToday variable in a query as needed
CONVERT (date, GETUTCDATE())
CONVERT (date, GETDATE())
CONVERT (date, '2022-18-01')
I don't know why the others recommend it with varchar(x) tbh.
https://learn.microsoft.com/de-de/sql/t-sql/functions/getdate-transact-sql