I have a sql 2008 database and I am creating a stored procedure that shall check if a datetime is more than 3 hours old but I don't know how to do it.
Do you have some way to do it?
the datetime is a field in the table.
BR
Rather than applying DATEDIFF to the column value, which will negate an index, I suggest using a comparison of the column to an expression (which can use an index).
If you want this as a filter:
SELECT columns
FROM dbo.table
WHERE DateTimeColumn < DATEADD(HOUR, -3, CURRENT_TIMESTAMP);
(If you want only the rows that are newer than 3 hours old, change < to > or >=.)
If you want to return all rows with a column showing whether it is more than 3 hours old:
SELECT columns, [3HoursOld] = CASE
WHEN DateTimeColumn < DATEADD(HOUR, -3, CURRENT_TIMESTAMP)
THEN 'Yes, older than 3 hours.'
ELSE 'No, not older than 3 hours.'
END
FROM dbo.table;
Take at look at the DATEDIFF function.
DATEDIFF ( datepart , startdate , enddate )
You would then use with datepart set to hh and the enddate set to the current time. To get the current database time you could use GETDATE(). Compare the result with 3 since it will return the number of hours passed.
#date is the date you want to compare
declare #date datetime
set #date= '2012-02-15 14:20:42.797'
SELECT DateDiff(hh, DATEADD(hh,-3,#date), GETDATE()) --if it's > 3
you better create a Boolean function that does the trick that you can use where ever you like
Related
I am (unsuccessfully) trying to set as default value to DATETIME a date based on another column that uses CURRENT_TIMESTAMP as default, but adding some days.
On MSSQL I used to do (dateadd(day,(5),[start_date])) as a "Computed Column Specification" to set the column end_date 5 days more that start_date column.
So, when I perform an INSERT I would like that start_date were set to NOW(); and end_date were set to [NOW(); + X days]
Is this even possible on MySQL?
Thanks in advance!
If you use an older version of MySQL and cannot use expressions in the DEFAULT clause as shown in the other answer, you can do this with a trigger.
CREATE TRIGGER mytrigger BEFORE INSERT ON t1
FOR EACH ROW BEGIN
SET NEW.start_date = CURDATE();
SET NEW.end_date = CURDATE() + INTERVAL 5 DAY;
END
As of MySQL 8.0.13, you can use expressions for default values.
It would allow you to call functions in your default. However, I do not believe you have the ability to query other columns (give it a try?)
You can use something like:
CREATE TABLE t1 (
...
start_date DATE DEFAULT (CURRENT_DATE),
end_date DATE DEFAULT (CURRENT_DATE + INTERVAL 5 DAY),
...
);
Do note the enclosing parenthesis is required for indicating it is an expression and not a literal.
Reference: https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html
This seems like overkill but is the only way I have been able to floor todays datetime to 00:00:00.000 at database level:
select CAST(FLOOR(CAST(CURRENT_TIMESTAMP AS float)) AS DATETIME)
I have tried using:
select FLOOR(getdate())
But get the following message:
Implicit conversion from data type datetime to float is not allowed. Use the CONVERT function to run this query.
Can anyone recommend another way of doing this?
Since you are using SQL Server 2008 you could make use of the date data type.
declare #Today date
set #Today = getdate()
select #Today
Or without the variable.
select cast(getdate() as date)
If you need to have the value as a datetime just cast it back to a datetime.
select cast(cast(getdate() as date) as datetime)
There are a lot of ways of doing this i have seen the floor one before. Here are a few more.
select cast(cast(CURRENT_TIMESTAMP as date) as datetime)
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SELECT CAST(CAST(CURRENT_TIMESTAMP - 0.50000004 AS int) AS datetime)
I normaly do the Cast to date version.
The title might be a bit misleading, but what I want is:
SELECT * FROM table ORDER BY pid ASC
And in one of the columns I have a DATE(). I want to compare the current date (not time) and return how many days are left till that date. Let's say the date is 2013-04-20 and today's date is 2013-04-16 I don't want to get any data if it's < current date. If it is I want it returned in days.
I've been looking around here and I've found no way to do it, and I can't for the love of me figure it out.
If you're looking for the difference between two date you can use the GETDATE function in MS SQL
SELECT DATEDIFF(DD, DateOne, DateTwo) FROM TABLE
This will return the difference in number of days between the two dates.
If you only want rows where the date field is less than or equal to today's date you can use:
SELECT DATEDIFF(DD, DateField, GETDATE())
FROM TableName
WHERE DateField <= GETDATE()
If you're using MySQL you can use DATEDIFF()
SELECT
DATEDIFF(NOW(), date_column) AS days_diff
FROM
tablename
Get the difference between two dates (ANSI SQL)
select the_date_column - current_date as days_left
from the_table
where the_date_column - current_date <= 4;
SQLFiddle: http://sqlfiddle.com/#!12/3148d/1
Am using Sql Server 2008, I have a column named Date in my table, and I want to get the datas for the particular date.... I need to give this Date in my WHERE condition.
for example, if I want to get the records for the particular month in the given date, how can I use this Date in WHERE condition.
DATANAME(MONTH,'#Date')
if I give like this in my query I can get the month from the given DATE, the same way I tried by putting in WHERE condition like,
WHERE DATE= DATANAME(MONTH,'#Date')
here it reports conversion error...how can I display the datas for a particular month, can anyone help me
If you want a month of data for a table you should check against an interval. The query is not able to use indexes on the date column if you are applying functions on the column.
Use something like this to get data for April 2012.
-- The date parameter
declare #Date datetime
set #Date = '2012-04-11'
declare #FromDate datetime
declare #ToDate datetime
-- set FromFate to first of april
set #FromDate = dateadd(month, datediff(month, 0, #Date), 0)
-- set ToDate to first of may
set #ToDate = dateadd(month, 1+datediff(month, 0, #Date), 0)
select *
from YourTable
where [Date] >= #FromDate and [Date] < #ToDate
If you want to show data for a particular year and month you can use the YEAR and MONTH functions:
SELECT ...
FROM ...
WHERE YEAR(mydate) = 2012 AND MONTH(mydate) = 3 -- March, 2012
To me it seems that your field Date is not of type varchar or nvarchar, so using a condition where a Datetime = string is obviously wrong.
Have you tried
WHERE DATE= #Date
Shouldn't it be:
DATENAME(MONTH, #Date)
Instead of:
DATANAME(MONTH,'#Date')
(Notice "DATA" vs "DATE" and #Date isn't in quotations)
Then to use this against a date/datetime column you would have to cast both sides like below:
WHERE datename(Month, [Date]) = datename(Month, [Date])
Warning: The above does not use any indexes so isn't as efficient as "WHERE Date = Date"
First: Remove '' from variable. #Date, not '#Date'
If you want to find dates from specific month. (You have to remember about year condition also)
WHERE DATANAME(MONTH, #Date) = 'April'
if you want to find exact date:
WHERE DATE = #date
Column d is DATE, column t is time, column v is, for example, INT. Let's say I need all the values recorded after 15:00 of 01 Feb 2012 and on. If I write
SELECT * FROM `mytable` WHERE `d` > '2012-02-01' AND `t` > '15:00'
all the records made before 15:00 at any date are going to be excluded from the result set (as well as all made at 2012-02-01) while I want to see them. It seems it would be easy if there were a single DATETIME column, but there are separate columns for date and time instead in the case of mine.
The best I can see now is something like
SELECT * FROM `mytable` WHERE `d` >= '2012-02-02' OR (`d` = '2012-02-01' AND `t` > '15:00')
Any better ideas? Maybe there is a function for this in MySQL? Isn't there something like
SELECT * FROM `mytable` WHERE DateTime(`d`, `t`) > '2012-02-01 15:00'
possible?
You can use the mysql CONCAT() function to add the two columns together into one, and then compare them like this:
SELECT * FROM `mytable` WHERE CONCAT(`d`,' ',`t`) > '2012-02-01 15:00'
The TIMESTAMP(expr1,expr2) function is explicitly for combining date and time values:
With a single argument, this function returns the date or datetime
expression expr as a datetime value. With two arguments, it adds the
time expression expr2 to the date or datetime expression expr1 and
returns the result as a datetime value.
This resulting usage is just what you predicted:
SELECT * FROM `mytable` WHERE TIMESTAMP(`d`, `t`) > '2012-02-01 15:00'
Here's a clean version that doesn't require string operations or conversion to to UTC timestamps across time zones.
DATE_ADD(date, INTERVAL time HOUR_SECOND)
All you have to do is to convert it into unix timestamp and make appropriate selections. For this you have to use mysql functions like *unix_timestamp().* and *date_format*
Suppose you want to select rows where timestamp > 1328725800, the following sql statement would do the task.
select unix_timestamp(d)+3600*date_format(t,'%h)+60*date_format(t,'%i')+date_format(t,'%S') as timestamp from table where timestamp>1328725800
Actually it should be:
SELECT * FROM `mytable` WHERE CONCAT(`d`,' ',`t`) > '2012-02-01 15:00:00'
If you want to take seconds into account, you need to add the two digits to the end ;)