let's say that I have a SmallDateTime column in my table. How to update hours in each row in T-SQL ?
Get the target value's hour part.
Find the difference between the hour you want and the found hour.
Add the difference of hours to the target value.
The script:
UPDATE atable
SET datetimevalue = DATEADD(hour, #hour - DATEPART(hour, datetimevalue),
datetimevalue)
WHERE ...
UPDATE YourTable SET YourDateColumn = DateAdd(hh, 1, YourDateColumn)
will add 1 hour to the time value in YourDateColumn in every single row.
See this page for more info.
UPDATE YourTableName
SET YourSmallDateTimeColumn = DATEADD(HH, 1, YourSmallDateTimeColumn)
Will add any number of hours to your column. So if you get rid of the time component first:
SELECT CAST(CONVERT(char(8), YourSmallDateTimeColumn, 112) AS smalldatetime)
and add hour component to it later it should work.
From here
To add or subtract hours to a datetime
or smalldatetime value, you will use
the DATEADD date function. The
DATEADD date function returns a new
datetime value based on adding an
interval to the specified date. The
syntax of the DATEADD date function is
as follows:
DATEADD ( datepart , number, date )
datepart is the parameter that
specifies on which part of the date to
return a new value. For hours, you
can use either HOUR or HH. number is
the value used to increment datepart.
date is an expression that returns a
datetime or smalldatetime value, or a
character string in a date format.
Here's an example on how to use the
DATEADD date function to increase or
decrease a datetime value by a certain
number of hours:
SELECT DATEADD(HOUR, -12, GETDATE())AS [TwelveHoursAgo]
SELECT DATEADD(HH, 6, GETDATE()) AS [SixHoursLater]
Related
I have a column called PairDt, a string that contains a date value in the last 5 characters. I want to compare that date value with the date value in the Day column, which contains dates in the YYYY-MM-DD format.
PairDt Day
----------------------------------
DCS-CNY-Yunbi-42606 2016-08-24
DCS-CNY-Yunbi-42607 2016-08-25
DCS-CNY-Yunbi-42608 2016-08-26
DCS-CNY-Yunbi-42609 2016-08-27
DCS-CNY-Yunbi-42610 2016-08-28
How do I convert Day to a value?
I'm trying to isolate Date values in PairDt that does not match the date value in Days
This 5 digit number at the end of PairDt looks like number of days since December 30th 1899. To convert this number to date use DATEADD to add as many days. To convert a date to number, use DATEDIFF to calculate the number of days. Something like this code:
declare #PairDt varchar(50) = 'DCS-CNY-Yunbi-42606', #Day date = '2016-08-24'
select DATEADD(d, cast(right(#PairDt, 5) as int), '1899-12-30'), DATEDIFF(day, '1899-12-30', #Day)
What's the easiest way to update a table that contains a DATETIME column on TSQL with RANDOM value between 2 dates?
I see various post related to that but their Random values are really sequential when you ORDER BY DATE after the update.
Assumptions
First assume that you have a database containing a table with a start datetime column and a end datetime column, which together define a datetime range:
CREATE DATABASE StackOverflow11387226;
GO
USE StackOverflow11387226;
GO
CREATE TABLE DateTimeRanges (
StartDateTime DATETIME NOT NULL,
EndDateTime DATETIME NOT NULL
);
GO
ALTER TABLE DateTimeRanges
ADD CONSTRAINT CK_PositiveRange CHECK (EndDateTime > StartDateTime);
And assume that the table contains some data:
INSERT INTO DateTimeRanges (
StartDateTime,
EndDateTime
)
VALUES
('2012-07-09 00:30', '2012-07-09 01:30'),
('2012-01-01 00:00', '2013-01-01 00:00'),
('1988-07-25 22:30', '2012-07-09 00:30');
GO
Method
The following SELECT statement returns the start datetime, the end datetime, and a pseudorandom datetime with minute precision greater than or equal to the start datetime and less than the second datetime:
SELECT
StartDateTime,
EndDateTime,
DATEADD(
MINUTE,
ABS(CHECKSUM(NEWID())) % DATEDIFF(MINUTE, StartDateTime, EndDateTime) + DATEDIFF(MINUTE, 0, StartDateTime),
0
) AS RandomDateTime
FROM DateTimeRanges;
Result
Because the NEWID() function is nondeterministic, this will return a different result set for every execution. Here is the result set I generated just now:
StartDateTime EndDateTime RandomDateTime
----------------------- ----------------------- -----------------------
2012-07-09 00:30:00.000 2012-07-09 01:30:00.000 2012-07-09 00:44:00.000
2012-01-01 00:00:00.000 2013-01-01 00:00:00.000 2012-09-08 20:41:00.000
1988-07-25 22:30:00.000 2012-07-09 00:30:00.000 1996-01-05 23:48:00.000
All the values in the column RandomDateTime lie between the values in columns StartDateTime and EndDateTime.
Explanation
This technique for generating random values is due to Jeff Moden. He wrote a great article on SQL Server Central about data generation. Read it for a more thorough explanation. Registration is required, but it's well worth it.
The idea is to generate a random offset from the start datetime, and add the offset to the start datetime to get a new datetime in between the start datetime and the end datetime.
The expression DATEDIFF(MINUTE, StartDateTime, EndDateTime) represents the total number of minutes between the start datetime and the end datetime. The offset must be less than or equal to this value.
The expression ABS(CHECKSUM(NEWID())) generates an independent random positive integer for every row. The expression can have any value from 0 to 2,147,483,647. This expression mod the first expression gives a valid offset in minutes.
The epxression DATEDIFF(MINUTE, 0, StartDateTime) represents the total number of minutes between the start datetime and a reference datetime of 0, which is shorthand for '1900-01-01 00:00:00.000'. The value of the reference datetime does not matter, but it matters that the same reference date is used in the whole expression. Add this to the offset to get the total number of minutes between the reference datetime.
The ecapsulating DATEADD function converts this to a datetime value by adding the number of minutes produced by the previous expression to the reference datetime.
You can use RAND for this:
select cast(cast(RAND()*100000 as int) as datetime)
from here
Sql-Fiddle looks quite good: http://sqlfiddle.com/#!3/b9e44/2/0
I have a table containing some datetime columns, now I want to get the timespan/interval between two columns in seconds (as int):
declare #Sessions TABLE
(
[session_id] [int] not null,
[start] [datetime] not null,
[end] [datetime] not null
)
insert into #Sessions([session_id], [start], [end])
values (1, '01.04.2012 08:15:05', '01.04.2012 08:16:40');
select [session_id], [end]-[start] as 'duration'
from #Sessions
What I get is a datetime like interval type: eg. 1900-01-01 00:01:35.000.
What I want is the timespan in seconds: eg. 95s.
Parsing the String should not be an option as I suppose that there's an easy to use function for that - deeply hidden in the msdn documentation, which I haven't found yet.
So, how to get those time intervals as int in seconds?
Change last select as
select [session_id],datediff(ss,[start],[end]) as 'duration' from #Sessions
I have tried the same below using table instead of table variable:
Using DATEDIFF, you can get the difference between 2 dates down to whichever resolution you want
e.g.
SELECT DATEDIFF(ss, start, end)
FROM #Sessions
SELECT [session_id]
, DATEDIFF(second, [start] - [end]) as 'Duration'
FROM #Sessions
DATEDIFF (Transact-SQL)
Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate.
I have column of type date time and values are getting stored in format 10-29-2011 08:25.
I would like to find out the rows only which are less then current date-time. What will be the condition for date comparison for current date and this date-time column field?
Thanks.
you could use the datetime function
SELECT * FROM mytable
WHERE mydate > datetime('now')
you can even make date operations
SELECT * FROM mytable
WHERE mydate > datetime('now','-15 days')
What I am trying to do is get a result from sql where the dates are in a certain range but its not working correctly, here is my query.
DECLARE #CurrDate DATETIME
SET #CurrDate = GETDATE()
SELECT dbo.ProductDetails.PartnerID
,dbo.ProductDetails.ProductID
,dbo.Products.ProductName
,StartDate
,EndDate
FROM dbo.ProductDetails
INNER JOIN dbo.Products
ON dbo.ProductDetails.ProductID = dbo.Products.ProductID
WHERE CONVERT(VARCHAR(10),StartDate,111) <= #CurrDate
AND CONVERT(VARCHAR(10),EndDate, 111) >= #CurrDate
but when the Enddate = #CurrDate the row does not show, but if i make that date just one day higher it gets displayed. Am i doing anything wrong? Any advice will do, thanks.
GetDate() returns date and time, while your conversion to varchar strips away the time part (I'm suspecting that's all it's actually supposed to do). So you would need to do the same conversion for #CurrDate.
If what you want is to simply consider the date only (ignoring the time part), you could use DATEDIFF instead of converting to varchar (see here); example:
DECLARE #CurrDate DATETIME
SET #CurrDate = GETDATE()
SELECT dbo.ProductDetails.PartnerID, dbo.ProductDetails.ProductID,
dbo.Products.ProductName , StartDate, EndDate
FROM dbo.ProductDetails INNER JOIN
dbo.Products ON dbo.ProductDetails.ProductID = dbo.Products.ProductID
-- where StartDate is on the same day or before CurrDate:
WHERE DATEDIFF(day, StartDate, #CurrDate) >= 0 AND
-- and where EndDate is on the same day or after CurrDate:
DATEDIFF(day, EndDate, #CurrDate) <= 0
If you want only DATE comparison, without time use the
cast(CONVERT(varchar, StartDate, 112) as datetime)
I am quite sure that the comparison takes into account the time as well as the date, in which case if the dates are the same but the current time is greater than the time being compared to you won't get that row as a result.
So, what you need to do is just extract the date part and compare those.
GETDATE() gives you date and time
if yours column have only date
then
CONVERT(VARCHAR(10),StartDate,111) <= #CurrDate
can give you unexpected result
remember
19.12.2011 14:41 > 19.12.2011 00:00
If you are using SQL 2008 or later, and wanting to compare only the date, not the time, you can also do:
Cast(StartDate as Date)
(This avoids having to convert to a string.)