TSQL - Calculating datediff in a query and setting a value? - sql-server-2008

Using SQL Server 2008, I want to calculate the timespan, in seconds, that has occurred between two times.
The start date, is the timestamp of the last occurance of where a specific ID exists (if the filter is true), get the time from that timestamp record, and do a DATEDIFF() against the current processing time and return a value, #LastEventTimespan, in seconds.
DECLARE #CurrentProcessTime DATETIME
DECLARE #LastEventTimespan DATETIME
SET #CurrentProcessTime = GetDate()
-- find the timespan since the last session event
-- DATEDIFF ( datepart , startdate , enddate )
SELECT MAX(PageVisitEventID) AS LastPageVisitEventID, #LastEventTimespan = DATEDIFF(second , DateAdded , #CurrentProcessTime )
FROM PageVisitEvents
WHERE UserID = #UserID
GROUP BY LastPageVisitEventID
I figured I could get the MAX ID of the filter and process accordingly but am unable to set the #LastEventTimespan, however trying to assign a value when doing data-retrieval is a no-no.
How can I get around this?
Thanks.

I guess you want something like this.
DECLARE #LastEventTimespan INT
SELECT TOP 1 #LastEventTimespan = DATEDIFF(SECOND, DateAdded, GETDATE())
FROM PageVisitEvents
WHERE UserID = #UserID
ORDER BY PageVisitEventID DESC
This will calculate the difference in seconds between DateAdded for the highest value of PageVisitEventID for a given user and the current DateTime. I changed the data type of #LastEventTimespan to INT because it probably makes more sense when dealing with seconds.

You can replace the SELECT statement with this one:
SELECT TOP 1
#LastEventTimespan = DATEDIFF(second , DateAdded , #CurrentProcessTime )
FROM PageVisitEvents
WHERE UserID = #UserID
ORDER BY PageVisitEventID desc
I've done such queries many times and never had problems.

Related

Fetch values between two dates - MariaDB version: 10.1.37

I'm trying to fetch values between two dates, specifically 24hrs
SELECT *
FROM `transactions`
WHERE accnum = '1534610376'
AND tdate BETWEEN 20190311 AND 20190312
This query works fine but, i don't want it for a constant date, i have checked and seen many format but none seems to work. please help
If you "want records from today alone" - a simple way would be:
WHERE accnum = '1534610376'
AND DATE(tdate) = CURRENT_DATE()
However - To utilize an index, a column should not be wrapped into a function. So an efficient way would be
WHERE accnum = '1534610376'
AND tdate >= CURRENT_DATE()
AND tdate < CURRENT_DATE() + INTERVAL 1 DAY
A good index for this query would be INDEX(accnum, tdate).
I suggest you to put your date between quots like this:
SELECT *
FROM `transactions`
WHERE accnum = '1534610376'
AND tdate BETWEEN '20190311' AND '20190312'
After, you can define a user defined function like this :
CREATE FUNCTION BetweenDate(#toCompare VARCHAR(30), #rightDate DATE, #leftDate DATE)
RETURNS TABLE
AS
BEGIN
RETURN (
SELECT *
FROM transactions
WHERE accum = #toCompare AND tdate BETWEEN #rightDATE AND #leftDate
)
END;

SQL - add days to a date in a loop

I have a table with this fields:
Id int(11) pk,
Start_date date,
End_date date,
type tinyint(1),
Frequency int.
I want to do a select on this table where start_date+frequency = #date(a variable date) until end_date(loop).
How do this with sql?
Thanks in advance.
EDIT:
Variable date is (for example):
SET #date = '2017-03-30'
type can be 0 or 1:
if type = 0 my query is :
select * from table
where type = 0 and start_date <= #date AND end_date>=#date
if type = 1, frequency is a field with an integer number(a interval of days). So I have to check if adding this value to start_date is equals to #date.
if yes, I have to return the current record
if no, I have to iterate this operation
Date current = start_date + interval of 'frequency' days
while(current < end_date){
if(current == #date)
(this is the record I want)
else
current+=frequency
}
The result of query of type 1 can be more than one record. And finally I want to UNION the result of type 0 and 1 in unique select.
Based on a comment/confirmation below the question:
So, to put it in less focussed on the wrong solution terms, you want to determine whether the difference between start_date and #date, in days, is an integer multiple of frequency? –
Looks like you want something like:
select * from table
where
start_date <= #date AND
end_date>=#date AND
(
type = 0 OR
(
type = 1 AND
mod(datediff(#date,start_date),frequency) = 0
)
)
Once we determined the actual requirement, above, and it was clear we just need to find out if one number is a multiple of another, we use mod to compute that. The rest of the structure of the WHERE clause essentially follows the bullet-pointed section of the question.

SQL Server 2008 DATEPART function

I need a query to update a column of DATETIME type by adding 2 hours only in Hours column using the DATEPART() function. Please help me out.
My query looks like this:
UPDATE logdetails
SET user_logouttime = DATEPART(HH, user_logouttime) + 2
WHERE id = (SELECT TOP 1 id FROM logdetails
WHERE user_id = 10
ORDER BY user_logintime DESC)
It just updates the time column with default value whereas I want only hours to be updated instead of entire time. Say if it's 2013-12-05:09:45:58, I want it to be 2013-12-05:11:45:58.
declare #no_hours int
set #no_hours = 2
declare #a datetime
set #a='2013-12-05 09:45:58'
select dateadd(HOUR, #no_hours, #a) as new_time_added
fiddle demo

How can I change a query inside a package to use the last execution datetime of job?

I have a daily job that runs a SSIS package to select the count of records from a table for the previous day using a date range. I want to change it to run every few minutes so I need to save the datetime used in the previous run query to a variable which I want to store in another DB table. It was suggested I store it using IO but not sure what they meant by that.
SELECT [authorUrl],[postDate] ,[dateadded]
FROM [Feeds].[dbo].[XMLFeed]
where CONVERT(DATE, DateAdded) = DATEADD(DAY, -1, CONVERT(DATE, SYSDATETIME()))
order by dateadded desc
How can I change the where statement to be where dateadded is equal to or greater than the last time this select was run.
You must stored the last execution value in a table somewhere. First, create a table to hold your last execution paramters :
create table LastExecutionParameters
(
Id int identity(1,1) not null,
LastExecutionDate datetime
)
Then, use it that way :
declare #executionDate datetime =
(select top 1 DateAdd(Day, 1, LastExecutionDate)
from LastExecutionParameters
order by Id desc);
SELECT [authorUrl],[postDate] ,[dateadded]
FROM [Feeds].[dbo].[XMLFeed]
where CONVERT(DATE, DateAdded) = DATEADD(DAY, -1, #executionDate)
order by dateadded desc
insert into LastExecutionParameters values (#executionDate);
Of course, change the dateadd call to fit your needs.

trying to figure out how to properly write a select for a dataset

table:
--duedate timestamp
--submissiondate timestamp
--blocksreq numeric
--file clob
--email varchar2(60)
Each entry is a file which will take blocksreq to accomplish. There are 8 blocks allotted per day (but could be modified later). before i insert into the table, i want to make sure there are enough blocks to accomplish it in the timeframe of NOW() and #duedate
I was thinking of the following, but i think i am doing it wrong:
R1 = select DAY(), #blocksperday - sum(blocksreq) as free
from table
where #duedate between NOW() and #duedate
group by DAY()
order by DAY() desc
R2 = select sum(a.free) from R1 as a;
if(R2[0] <= #blocksreq){ insert into table; }
pardon the partial pseudocode.
SQL FIDDLE: http://sqlfiddle.com/#!2/5bda5
warning: My sql fiddle has garbage code... as i dont know how to make a lot of test cases. nor set the duedate to NOW()+5 days
Something like this? (wasn't sure how partial days were handled so ignored that part)
CREATE TABLE `DatTable` (
`duedate` datetime DEFAULT NULL,
`submissiondate` datetime DEFAULT NULL,
`blocksreq` smallint(6) DEFAULT NULL
)
SET #duedate:='2012-10-15';
SET #submissiondate:=CURRENT_TIMESTAMP;
SET #blocksreq:=5;
INSERT INTO DatTable(duedate,submissiondate,blocksreq)
SELECT #duedate,#submissiondate,#blocksreq
FROM DatTable AS b
WHERE duedate > #submissiondate
HAVING COALESCE(SUM(blocksreq),0) <= DATEDIFF(#duedate,#submissiondate)*8-#blocksreq;