I have a console app that will choose records based on if the user has chosen to be notified daily at a specific hour of the day as well as all records where the user has chosen hourly.
The job will run every 15 minutes.
How do I find a threshold of time between 5 minutes before and 5 minutes after the top of the hour?
This is my code
Declare #Now datetime
Declare #NowHour int
Declare #NowMinute int
Declare #NewNow nvarchar(50)
Set #Now = {fn Now()}
Set #NowHour = (SELECT DATENAME(hh, #Now))
Set #NowMinute = (SELECT DATENAME(mi, #Now))
Set #NewNow = Cast(Cast(#NowHour As nvarchar(2)) + ':' + Cast(#NowMinute As nvarchar(2)) as Time)
Select #Now, #NowHour, #NowMinute, #NewNow
Select * From vw_consumerAlerts
Where casexid not in
(Select casexid from alerthistory)
And Name = 'Always'
Or ([Hour] Between DateAdd(minute, -5, #NewNow) And DateAdd(minute, -5, #NewNow))
This is the error I'm getting
The data types time and datetime are incompatible in the greater than or equal to operator.
I got it, I had [Hour] and #NewNow swapped, now I get the correct results with:
(#NewNow Between DateAdd(minute, -5, [Hour]) And DateAdd(minute, 5, [Hour]))
Assuming you have defined #TheHour as being the hour in question with 00 minutes/seconds:
WHERE mydatecol BETWEEN DATEADD(minute, -5, #TheHour) AND DATEADD(minute, 5, #TheHour)
UPDATE
See this:
select 1
where cast('1/1/2010 1:04pm' as time)
between cast('1/1/2010 12:55pm' AS time)
and cast ('1/1/2010 1:05pm' as time)
time and datetime are different, so you need to cast your datetime to time as I've done in the crude example here.
So in your case:
Select * From vw_consumerAlerts
Where casexid not in
(Select casexid from alerthistory)
And Name = 'Always'
Or ([Hour] Between cast(DateAdd(minute, -5, #NewNow) as time)
And cast(DateAdd(minute, -5, #NewNow) as time))
Related
I come in to work 6.30am, and need to audit what happened from 5pm when I left to 6.30am this morning. I have used code to search 13.5 hours back from any given time:
SELECT * FROM TRANSACTION_HISTORY
WHERE TRANSACTION_HISTORY.ACTIVITY_DATE_TIME > (SELECT DATEADD(hour,-13.5,(SELECT MAX (TRANSACTION_HISTORY.ACTIVITY_DATE_TIME) FROM TRANSACTION_HISTORY)))
Problem is if I run query later, I lose time from the start, eg. If I run query at 7am, I only get results from 5.30pm onwards. Rather than change criteria every day, I wanted to able to search from 6.30am of the current day, back to 5.30pm of the previous day. Can this be done?
Normally, I don't advise using between for datetime, because the boundary conditions can cause confusion. I don't think that is the case.
Here is one method:
SELECT *
FROM TRANSACTION_HISTORY th
WHERE th.ACTIVITY_DATE_TIME between cast(cast(getdate() -1 as date) as datetime) + 17.5/24.0
cast(cast(getdate() as date) as datetime) + 6.5/24.0;
The expression cast(cast(getdate() as date) as datetime) is truncating the datetime value to midnight. As a datetime, SQL Server lets you add a number which is understood as a fraction of a day. Hence, 17.5/24 represents "5:30". This addition doesn't work for the date data type.
You can do this.
DECLARE #dt datetime
DECLARE #dt1 datetime
DECLARE #dt2 datetime
SET #dt = CONVERT(datetime, CONVERT(VARCHAR(10), getdate(), 101 ), 101)
SET #dt1 = dateadd(mi, 30, dateadd(hh, 6, #dt))
SET #dt2 = dateadd(mi, -27*30, #dt1)
SELECT #dt1 as StartDate, #dt2 as EndDate
For additional details what this script does you may check these pages.
http://technet.microsoft.com/en-us/library/ms174450%28v=sql.105%29.aspx
http://technet.microsoft.com/en-us/library/ms186819%28v=sql.105%29.aspx
I have an if statement in a stored procedure that is being used to derive some time value. It looks like this:
DECLARE #foo TIME
IF (SELECT CONVERT(TIME,SYSUTCDATETIME())) > '15:00'
SET #foo = DATEADD(hh,-15,CONVERT(TIME,SYSUTCDATETIME()))
ELSE
SET #foo = DATEADD(hh,+9,CONVERT(TIME,SYSUTCDATETIME()))
later on i would like to use that value in the following WHERE clause:
AND created_at > DATEADD(hh,-#DailyLimitOffsetTime, CONVERT(TIME,SYSUTCDATETIME()))
I keep on getting an error that the data type time is invalid for the minus operator. How can i get around this to make the and clause work. I have tried converting the data type and i somewhat understand the issue DATEADD(hh) is looking for param 2 to be an int not a time. Is there some easier way to do this, I must admit if you couldn't tell already I am not good with timestamps at all. Any help is appreciated.
DECLARE #DailyLimitOffsetTime TIME
IF (SELECT CONVERT(TIME,SYSUTCDATETIME())) > '15:00'
SET #DailyLimitOffsetTime = DATEADD(hh,-15,CONVERT(TIME,SYSUTCDATETIME()))
ELSE
SET #DailyLimitOffsetTime = DATEADD(hh,+9,CONVERT(TIME,SYSUTCDATETIME()))
IF #Limit <=
(
SELECT COUNT(*)
FROM dbo.fooTable
WHERE offerId = #OfferID
AND created_at >
DATEADD(hh,DATEPART(hh,-#DailyLimitOffsetTime),CONVERT(TIME,SYSUTCDATETIME()))
)
SET #ErrorTypeID = 9400
I am sure there is a much better way to do this, and if so please share how. As always any help is appreciated. If you need any further explanation on the issue let me know. Its a bit messy this one.
Second argument in DATEADD function has to be resolved to an int
AND created_at > DATEADD(hh, -DATEPART(hh, #DailyLimitOffsetTime), CONVERT(TIME,SYSUTCDATETIME()))
OR
DECLARE #time time = CONVERT(TIME, SYSUTCDATETIME())
IF #Limit <=
(
SELECT COUNT(*)
FROM dbo.fooTable
WHERE offerId = #OfferID
AND created_at >
CASE WHEN #time > '15:00'
THEN DATEADD(hh, 15, DATEADD(hh, -DATEPART(hh, #time), #time))
ELSE DATEADD(hh, 09, DATEADD(hh, -DATEPART(hh, #time), #time)) END
END
)
SET #ErrorTypeID = 9400
I don't get what you are doing as you will always make the same time and not account for the date just the time. You don't want that if you are trying to show a different day forward when the UTC time is after 3 PM at a location. So if you want to go nine hours ahead you won't because you are only accounting for the current day by using the time frame. So if it was 8 PM of 1-16-12 you would set the time to be 5 AM. I think you need to set the DATETIME for what you want, not just the time.
DECLARE #foo Datetime
IF (SELECT CONVERT(TIME,SYSUTCDATETIME())) > '15:00'
SET #foo = Dateadd(hh, datediff(hh, 0, sysutcdatetime()) -15, 0)
ELSE
SET #foo = Dateadd(hh, datediff(hh, 0, sysutcdatetime()) + 9, 0)
select #foo
I am trying to do the following:
Format GetDate() to display only the minutes
Format a varchar column to display only the minutes
Subtract the current time HH:MM:SS from GetDate() and the VarChar column
This is what I have
CONVERT(VARCHAR(5), GETDATE(), 108) - substring(convert(varchar(20), ColumnName, 9), 13, 5)
but I am getting this error and need some help please:
Operand data type varchar is invalid for subtract operator.
What you want is datepart(mi).
To get the minutes for getdate():
select datepart(mi, getdate())
To subtract a number of minutes from a datetime:
select dateadd(mi, - <minutes>, <datevalue>)
To remove the time from getdate(), just cast to date (in more recent versions of SQL Server):
select cast(getdate() as date)
To get the difference in minutes, use datediff:
select datediff(mi, <datestart>, <dateend>)
What are you really trying to accomplish?
I think this is what you want:
declare #str varchar(30)
set #str = '2012-08-14 10:12:02.690'
select datediff(minute, cast(#str as datetime), getdate())
Results when getdate() = '2012-08-14 11:21:10.250' is total minutes even over 60:
69
If you are familiar with Microsoft Log Parser you probably recognize the Quantize function which will truncate a value to the nearest multiple of another value. It is quite handy for grouping date-time fields into increments.
Date-Time Count
1/1/2010 00:00 100
1/1/2010 00:15 134
1/1/2010 00:30 56
....
I'm trying to find a similar function in Transaction-SQL (specifically SQL Server 2005 or 2008) that will allow me to do a similar grouping on date-time.
You can round to any given number of minutes like so:
DateAdd(Minute, (DateDiff(minute, 0, getutcdate() )/15) * 15, 0)
Instead of using getutcdate() you can use your date column, variable or expression. In addition the number of minutes can be a variable.
declare #minutesQuantize int set #minutesQuantize = 15
DateAdd(Minute, (DateDiff(minute, 0, getutcdate() )/#minutesQuantize) * #minutesQuantize, 0)
The only rule is that the date difference must fit into an integer, I.e. be less than 2 billion. That means you can't do seconds or milliseconds without a more complicated expression.
If you need seconds or milliseconds do this:
dateadd(ms, (datediff(ms, dateadd(day, datediff(day, 0, #date), 0), #date)/#msInterval)*#msInterval, dateadd(day, datediff(day, 0, #date), 0))
Or, if you want to wrap this into a function:
create function dbo.DateRoundMinutes(#dt datetime, #minutes int)
returns datetime
as begin
return DateAdd(Minute, (DateDiff(minute, 0, #dt )/#minutes) * #minutes, 0)
end
go
create function dbo.DateRoundMilliseconds(#dt datetime, #ms int)
returns datetime
as begin
return dateadd(ms, (datediff(ms, dateadd(day, datediff(day, 0, #dt), 0), #dt)/#ms)*#ms, dateadd(day, datediff(day, 0, #dt), 0))
end
Which you can use like this:
select t.dt,
dbo.DateRoundMilliseconds(dt, 500) dt0_5Second, -- Half second
dbo.DateRoundMilliseconds(dt, 5000) dt5second, -- 5 second
dbo.DateRoundMilliseconds(dt, 15000) dt15Second,
dbo.DateRoundMilliseconds(dt, 90000) dt90Second,
dbo.DateRoundMinutes(dt, 2) dt2Minute,
dbo.DateRoundMinutes(dt, 5) dt5Minute,
dbo.DateRoundMinutes(dt, 15) dt15Minute,
dbo.DateRoundMinutes(dt, 90) dt90Minute
from
/* some table having a column dt */
Not directly, it doesn't. But you can group by a function (that you write) that rounds the datetime column to its nearest quarter-hour (or whatever Quantize does).
SELECT
dbo.QuarterHour(DateColumn) AS Date-Time
, COUNT(*) AS Count
FROM MyTable
GROUP BY dbo.QuarterHour(DateColumn)
how to enter manual time stamp in get date () ?
select conver(varchar(10),getdate(),120)
returns 2010-06-07
now i want to enter my own time stamp in this like
2010-06-07 10.00.00.000
i m using this in
select * from sample table where time_stamp ='2010-06-07 10.00.00.000'
since i m trying to automate this query i need the current date but i need different time stamp can it be done .
You just want to append a time to your result? Like this?
select convert(varchar(10),getdate(),120) + ' 10.00.00.000'
or if you want to get it back to a DATETIME type:
select convert(datetime,convert(varchar(10),getdate(),120) + ' 10:00')
--SQL Server 2008
DECLARE #MyTime time, #MyDate date
SELECT #MyDate = GETDATE(), #MyTime = '10:00:00'
SELECT CAST(#MyDate AS datetime) + #MyTime
--SQL Server 2005 and before
DECLARE #MyTime datetime, #MyDate datetime
SELECT
#MyDate = DATEADD(day, 0, DATEDIFF(day, 0, GETDATE())),
#MyTime = '19000101 10:00:00'
SELECT #MyDate + #MyTime
"zero" date = 01 Jan 1900 in SQL Server
SELECT DATEADD(hh, 1, FLOOR(CAST(GETDATE() AS FLOAT)))
Once you have the floor of the date, you can add time to it.
DATEADD(datepart, number, date)