I have start time and end time in my application. I now need to check if there is any time falling between those time in SQL Query.
How do I write the query.
Thanks
This should work for you.
Select * From MyTable
Where timecreated Between Cast('7/20/08 12:01:01' As DateTime) And Cast('7/20/09 12:01:01' as DateTime)
I would recommend to not use between when comparing datetime. The result is often not what you want.
BETWEEN returns TRUE if the value of
test_expression is greater than or
equal to the value of begin_expression
and less than or equal to the value of
end_expression.
Test data for demo
declare #T table (dt datetime)
insert into #T values('2011-04-12T09:00:00')
insert into #T values('2011-04-12T10:00:00')
insert into #T values('2011-04-12T11:00:00')
insert into #T values('2011-04-12T12:00:00')
Query using between
select *
from #T
where dt between '2011-04-12T10:00:00' and '2011-04-12T11:00:00'
Result: 11:00 is included in the result.
dt
2011-04-12 10:00:00.000
2011-04-12 11:00:00.000
Rewrite the query using >= and < instead.
select *
from #T
where
dt >= '2011-04-12T10:00:00' and
dt < '2011-04-12T11:00:00'
Result
dt
2011-04-12 10:00:00.000
The title of the question hints at that you want to check for overlapping date intervals. If that is the case you can have a look at this question How can I determine in SQL Server if a dateTime range overlaps another.
This will also work :-
select * from tablename where time between '7/7/2009 12:35:35' and '7/7/2010 23:35:35'
Related
Given a specified time value and an interval value:
Specified Time: 13:25:00
Interval Value: 00:20:00
How can I filter the following table of values to return times that are the specified Interval either side of the Specified Time.
12:45:24
13:05:00
13:50:30
14:50:32
15:15:10
I want a function or query to check if '13:25:00' has '00:20:00' difference with any of the times in table.
The output should return:
13:05:00
Based on the information you have provided, I assume you want to get values from the list that are the specified period either side of your "special time".
Here's one way to do it using DATEADD:
-- temp table for your sample data
CREATE TABLE #times ( val TIME )
INSERT INTO #times
( val )
VALUES ( '12:45:24' ),
( '13:05:00' ),
( '13:50:30' ),
( '14:50:32' ),
( '15:15:10' )
DECLARE #special_time TIME = '13:25:00'
DECLARE #diff_value TIME = '00:20:00'
-- variable will hold the total number of seconds for your interval
DECLARE #diff_in_seconds INT
-- gets the total number of seconds of your interval -> #diff_value
SELECT #diff_in_seconds = DATEPART(SECOND, #diff_value) + 60
* DATEPART(MINUTE, #diff_value) + 3600 * DATEPART(HOUR, #diff_value)
-- get the values that match the criteria
SELECT *
FROM #times
WHERE val = DATEADD(SECOND, #diff_in_seconds, #special_time)
OR val = DATEADD(SECOND, -( #diff_in_seconds ), #special_time)
DROP TABLE #times
Note that the WHERE clause filters the results by adding and subtracting the difference. The subtraction is achieved by making the #diff_in_seconds negative.
If we are understanding your question correctly, you want all the times that are bigger than 20 minutes from your given (special) time.
To achieve this, just do a select with a where clause that contains a clause looking like this: abs(datediff(minute, tableDate, #specialdate)) > 20
SQLFiddle sample and code example:
declare #specialDate datetime = '1900-01-01 13:25:00'
select *
from SampleData
where abs(datediff(minute, SomeDate, #specialDate)) > 20
Note that I set the dates of the Datetime columns to 1900-01-01 as an obscure reference, adjust according to your settings.
You will need the ABS in the line to make sure that both variants of the resulting datediff are checked (It can either bring back 0, > 0 or < 0)
References:
MSDN: DATEDIFF
MSDN: ABS
Here is a solution:
create table t(t time);
insert into t
values
('12:45:24'),
('13:05:00'),
('13:50:30'),
('14:50:32'),
('15:15:10')
declare #st time = '13:25:00'
declare #dt time = '00:20:00'
select * from t
where abs(datediff(ss, t, #st)) - datediff(ss, '00:00:00', #dt) = 0
abs(datediff(ss, t, #st) will hold difference in seconds between times in table and special time. You compare this difference to difference between 00:00:00 and interval datediff(ss, '00:00:00', #dt)
Output:
t
13:05:00.0000000
Fiddle http://sqlfiddle.com/#!6/05df4/1
I'm trying to set a column with a default value or binding of the current date in MSSQL.
I'm currently using GETDATE(), but this gives me the timestamp with the hours, minutes, seconds and milliseconds, I only need the day part (2015-03-05).
Only results I found on the web were these of changing it in the SELECT statement.
If you use it in a date context SQL Server will auto cast it for you
DECLARE #date DATE = GETDATE();
SELECT #date
-- result: 2015-03-05
or you could simply use a cast
SELECT CAST(GETDATE() as DATE)
EDIT:
I'm still not sure if I get what you want, but if you want to do it as a default constraints it works the same way:
create table #table
(
id int,
insertDate date default GETDATE()
)
insert into #table (id) values (1)
select top 1 insertDate from #table
-- result: 2015-03-05
If you want to store only date, excluding time you can use this:
CREATE TABLE #dts(id INT IDENTITY, d_date datetime2 DEFAULT CONVERT(char(10), GETDATE(), 126))
INSERT #dts DEFAULT VALUES
SELECT * FROM #dts
However it will return you zeroes instead of time, as seen here:
id d_date
-------------------------------
1 2015-03-05 00:00:00.0000000
You can remove unwanted characters using LEFT function:
SELECT id, LEFT(d_date, 10) FROM #dts
It will return you:
id d_date
--------------
1 2015-03-05
You could achieve this by using varchar as datatype, but i dont think it would be appropiate solution and it's better to format date in select statement. But if you really need it, then this works:
CREATE TABLE #dts(id INT IDENTITY, d_date VARCHAR(10) DEFAULT CONVERT(char(10), GETDATE(), 126))
INSERT #dts DEFAULT VALUES
SELECT * FROM #dts
Output:
id d_date
--------------
1 2015-03-05
Set your default value on the column to
(CONVERT([date],getdate(),0))
I have used it many times
In other ways to convert DATETIME to DATE (get only date without time) you can use CAST to DATE format.
SELECT CAST(GETDATE() AS DATE)
In your case you can set default value type DATE without CASTing.
CREATE TABLE #TempTable
(
Id INT,
..... ,
CurrentDate DATE DEFAULT GETDATE()
)
The answer to your problem is simple. Change the format of the column that is going to hold the value to a DATE (as opposed to a data type that will hold the time portion, i.e: DATETIME).
Then set the default to GETDATE() and because the destination column is a DATE the time portion will be stripped off for you.
Take this sample code:
CREATE TABLE #temp (id INT, CreatedDate DATE DEFAULT GETDATE())
INSERT INTO #temp ( id)
VALUES ( 1 ),( 2 ),( 3 )
SELECT * FROM #temp
DROP TABLE #temp
Output:
id CreatedDate
1 2015-03-05
2 2015-03-05
3 2015-03-05
You can use CONVERT() to get date in different formats. From http://www.w3schools.com/sql/func_convert.asp :
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
gives you the following results:
Nov 04 2011 11:45 PM
11-04-11
11-04-2011
04 Nov 11
04 Nov 2011
04 Nov 2011 11:45:34:243
i'm trying to do this line of sql script
select *
from content
where first_broadcast_date <= CONVERT(datetime, '26-11-2014', 105)
the result show me the content which have the value of 'first_broadcast_date' less than '26-11-2014' but not the content which have 'first_broadcast_date = 26-11-2014'
the type of 'first_broadcast_date' field is datetime2(7)
because its a date time field you either have a choice to convert to date might give you a bad performance or you can pass date by concatenating 23:59:59 so that you can filter any row in that day
CREATE TABLE #t (id INT IDENTITY(1,1), d DATETIME2(7))
INSERT INTO #t (d)
VALUES(GETDATE())
SELECT * FROM #t WHERE d <= '02/12/2015 23:59:59'
I have a table having two columns (date_ID, entry_Date). I want to insert all the dates within a specific time period into the table (say dates all the dates between 2002-2030). Is there any way to do that using loops in SQL-Server?
Try this
DECLARE #d date='20020101'
WHILE #d<'20300101'
BEGIN
INSERT INTO dbo.Dates (entry_Date)
VALUES (#d)
SET #d=DATEADD(DAY,1,#d)
END
GO
This should do it:
WITH TestItOut AS
(
SELECT CAST('2002-01-01' as datetime) DateColumn
UNION ALL
SELECT DateColumn + 1
FROM TestItOut
WHERE DateColumn + 1 <= '2030-12-31'
)
INSERT INTO YourTable (ColumnName)
SELECT DateColumn
FROM TestItOut
OPTION (MAXRECURSION 0)
in oracle i would do
insert into sometable
select to_date('01/01/2013','dd/mm/yyyy') + level
from dual
connect by level < 10001
this will generate 10000 dates from 1/1/13 with a daily interval. if you want hourly interval for example you can just change + level to + level/24.
this is basic ANSI sql hierarchical query - it should work in SQL server as well.
insert into table values(date_ID,(select entry_Date from table where entry_Date between 01/01/2002 and 01/01/2030))
Try this kind of query.
In place of date_ID put your appropriate value.
How do I add time to a datetime field with an indexing value?
My RDBMS is SQL Server 2008 R2.
I want to start at noon for a datetime field and for every record, take the base value of noon and add 15 seconds and set it for the record.
Example
Record 1: DateTime Value = '12:00:00 pm'
Record 2: DateTime Value = '12:00:15 pm'
Record 3: DateTime Value = '12:00:30 pm'
...n...
I toyed with a UPDATE query, but I couldn't get it to index. I'm feeling this might require a function, but I'm not sure.
Ideas?
Respectfully,
Ray
Assuming that you have a table YourTable with a datetime column Value that you need to fill with a datetime value incremented by 15 seconds for each row. Here I use a column ID to specify the order of the rows.
declare #Start datetime = '2011-05-18T12:00:00'
;with cte as
(
select Value,
row_number() over(order by ID) as rn
from YourTable
)
update cte set
Value = dateadd(s, 15*(rn-1), #Start)
With a recursive CTE (Common Table Expression) you could do this pretty easily:
;WITH DateTimes AS
(
SELECT
CAST('2011-05-18T12:00:00pm' AS DATETIME) AS YourTime,
1 AS RowNum
UNION ALL
SELECT
DATEADD(SECOND, 15, dt.YourTime),
dt.RowNum + 1
FROM
DateTimes dt
WHERE
dt.RowNum < 50
)
SELECT *
FROM DateTimes
Mind you: you need to make sure yourself to stop the recursion before the default max recursion depth of 100 has been reached (that's what I use the RowNum column for) - otherwise, SQL Server will tell you loud and clear that it doesn't like this recursive CTE :-)
This produces an output of:
YourTime RowNum
2011-05-18 12:00:00.000 1
2011-05-18 12:00:15.000 2
2011-05-18 12:00:30.000 3
2011-05-18 12:00:45.000 4
....
....
2011-05-18 12:12:00.000 49
2011-05-18 12:12:15.000 50
So if you have a DATETIME value that has no time like this:
DECLARE #Today DATETIME
SET #Today = CAST(GETDATE() AS DATE)
SELECT #Today -- gives: 2011-05-18 00:00:00.000
you could easily add time values to it from your recursive CTE (you could even adapt it to return only TIME and add that to your DATETIME column):
SELECT
CAST(YourTime AS TIME),
#Today + CAST(YourTime AS TIME) AS 'NewValue'
FROM TimeValues
Look at the DATEADD function and this may help you.
http://msdn.microsoft.com/en-us/library/ms186819.aspx