Subtract two dates in Microsoft SQL Server - sql

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.

Related

SQL Server error in conversion of date from string

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.

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

How to filter only the date from a string stored in a varchar

Ii have values stored in the SQL Server in the following manner : 02-Jul-12 12:00:00 AM here the time and minutes, seconds can be anything like 02-Jul-12 12:15:52 PM ,02-Jul-12 6:02:12 AM so on.
I want to have a where condition which will omit the time and take the data based on the date like the following where some_Date='02-Jul-12'
How would I do this?
SELECT * FROM whatever WHERE some_Date LIKE '02-Jul-12%';
If you are on SQL2008 or later, you can cast your DATETIME to DATE.
See this post: http://blog.sqlauthority.com/2012/09/12/sql-server-get-date-and-time-from-current-datetime-sql-in-sixty-seconds-025-video/
But in a WHERE-clause it is better to search between dates, like this:
DECLARE #startDate DATETIME = '02-Jul-2012'
DECLARE #endDate DATETIME = DATEADD(DAY, 1, #startDate)
SELECT * FROM [table] WHERE [some_Date] BETWEEN #startDate AND #endDate
SELECT * FROM dbo.tbl_MyTable
WHERE
REPLACE(CONVERT(VARCHAR(9), DateTimeValueColumn, 6), ' ', '-')='02-Jul-12'
or
On chage in code is instead of using getdate function voncert you datestring in datetime format and do compare this follow query will work for you
SELECT * FROM dbo.tbl_MyTable
WHERE
CAST(CONVERT(CHAR(10), DateTimeValueColumn, 102) AS DATE) =
CAST(CONVERT(CHAR(10),GETDATE(),102) AS DATE)
If you are storing dates as characters -- which is not recommended -- you should at least use ISO format: YYYY-MM-DD hh:mm:ss. This makes the date useful for sorting and comparisons ("<" works, ">" works, "between" works as well as equals).
To extract the date, you can then use left(datestr, 10). In your format, you would use:
where left(datestr, 9) = '01-Jan-13'
If you are storing the fields as a datetime or smalldatetime, you may think they are stored as a string. They are not. They are stored as some number of days since some particular date, with day parts stored as fractional days. If you are using SQL Server 2005 or greater, then the best way is:
where cast(datetime as date) = '2013-01-01' -- I recommend ISO formats, even for constants. '20130101' is even better
To select rows with today's date (not time)
select * from myTable where datediff(dd, dateColumn, getdate()) = 0

Microsoft SQL Server 2008 - Dates

I have a couple of questions in regards to dates in SQL Server.
How do I separate a datetime value "2011-08-10 14:56:17.267" into date and timestamp in two separate columns. Eg. Date "2011-08-10" and timestamp "14:56:17"
I want remove the timestamp from datetime value into "2011-08-10" and still be able to order the data by date (therefore not converted to varchar). Also is there away to change the date value as '10 Aug 2011' and still can sort (not alphabetically but in real date order).
Thank you,
HL
For the first one:
UPDATE atable
SET
DateColumn = CAST(DateTimeColumn AS date),
TimeColumn = CAST(DateTimeColumn AS time)
As for the second one, date display format is something that is unrelated to the date value. You can order the result set by your date column, but in the SELECT clause you can use CONVERT to display the date in the desired format. For example:
SELECT
CONVERT(varchar, DateColumn, 106) AS Date,
…
FROM atable
ORDER BY DateColumn
use CONVERT function with parameters from resource http://www.mssqltips.com/tip.asp?tip=1145
-- simple conversion example:
SELECT CONVERT(VARCHAR(10), GETDATE(), 102) -- for date
SELECT CONVERT(VARCHAR(10), GETDATE(), 8) -- for time

Please tell me what is error in my date comparison sql query

Please help me to find out error in my SQL query. I have created this query to compare dates
select * from Joinplans jp
where cast(convert(varchar,GETDATE(),103) AS datetime) BETWEEN
CASE(convert(varchar,jp.planstartDate,103) AS datetime) AND
CASE(convert(varchar,DATEADD(DAY,jp.planDays,jp.planstartDate),103) AS DATETIME)
It's giving me the error:
incorrect near 'AS'
I am using SQL Server 2005.
You wrote case instead of cast in two instances.
If planStartDate is actually a date, then there is no need to cast it to a character column:
Select ...
From Joinplans jp
where GetDate() Between planStartDate And DateAdd(day, jp.planDays, jp.planStartDate)
Now, if planStartDate is storing both date and time data, then you might want to use something like:
Select ...
From Joinplans jp
Where planStartDate <= GetDate()
And GetDate() < DateAdd(day, jp.planDays + 1, jp.planStartDate)
This ensures that all times on the last date calculated via the DateAdd function are included