views:

68

answers:

4

I am facing a problem for writing an sql query which should be easy I guess but I am not able to concentrate on that query. Hence taking some help from this website.

Problem: I have an table "Request" which has following columns -

CreatedOn: When I create new request, the CreatedOn is filled up with current datetime

LastModifiedOn: When somebody modifies the record, this field is updated with that modified current datetime. By default, this is equal to createdOn when request is first created.

Now logic to check is - Initially the request state is "Submitted". If the request is not modified for next 10 minutes or in 10 minutes interval, then the request state should get updated to "Cancelled". Now I am not able to get how to write this query.

EDIT: if the request is modified in any 10 mins interval, then I dont want to update request to cancelled. i.ei In general I want to update status to cancelled only if the record is not modified in last 10 mins

Let me know if any other details are required. You can assume there is also a RequestID column which is unique.

+1  A: 
update Request 
set State='Cancelled' 
where State='Submitted' AND dateadd(mi, -10, GetDate()) < ModifiedOn
tster
@Tster - This will not check if the record was modified at all. I do not want to update status to cancelled if record was modified in last 10 mins
Sachin Shanbhag
@Sachin Shanbhag, you can't modify it by replacing CreatedOn with ModifiedOn?
tster
@Tster - I know Buddy. I did not say your answer was wrong. I tried your answer with replacing createdOn with lastModifiedOn but did you realise your query will always return true because you are adding 10 to current date which can never be less than lastModifiedOn or createdOn. Thanks.
Sachin Shanbhag
Oops, yes that was a mistake. I fixy.
tster
+4  A: 
update Request 
set State = 'Cancelled' 
where RequestID = @MyRequestID
    and State = 'Submitted' 
    and LastModifiedOn < dateadd(mi, -10, getdate()) 

Note: This query is designed to be SARGable for best performance by not using LastModifiedOn in a function.

RedFilter
@RedFilter - Yes, Thanks, I am looking at this similar kind of solution where I dont want to use lastModifiedOn or craetedOn in a function. Let me try and get back on this.
Sachin Shanbhag
+1  A: 

update Request set State='Cancelled', LastModifiedOn=getdate() where State = 'Submitted' and datediff(min, LastModifiedOn, getdate()) > 10

Valery
+1  A: 

Are you looking for DateDiff?

DATEDIFF(minute, LastModifiedOn, getdate()) > 10
Mouhannad
Thanks, but no datediff
Sachin Shanbhag