0

I have a table

ID | DATE
1  |  16-01-2012
2  |  17-01-2012
3  |  18-01-2012
4  |  22-01-2012
5  |  28-01-2012
6  |  02-02-2012

My task is:

I have a date variable which is initialised to 16-01-2012 and I have to find all rows which are in continuum with 16-01-2012 i.e 17-01-2012 and 18-01-2012.

Please help.

0

2 Answers 2

6

One possibility would be to use a hierarchical query like the following:

with data (id, date)
as
(
    select id, date from yourtable where date = '16-01-2012'
    UNION ALL
    select t.id, t.date
    from yourtable t
    inner join data d 
      on  DATEDIFF(dd, d.date, t.date) = 1
    -- 1 day difference
)
select
    *
from
    data
;

I don't have an SQL server here to try this out, so there might be some errors in the statement. It should give you an idea though.

Sign up to request clarification or add additional context in comments.

6 Comments

on DATEDIFF(dd, t.Date, d.Date) = -1
@AdrianIftode: Thanks. Isn't simple subtraction working in SQL server?
@AdrianIftode: Why exactly? Doesn't SQL server support subtraction of dates that way?
"Operand data type date is invalid for subtract operator." I suppose they can't decide what the difference means, is it about days, months, years etc.
@AdrianIftode: Thanks - I assumed it worked the same way as in Oracle. There it is a decimal representing the difference in days.
|
-1

Try this:

select id, date 
from table 
where date > date_from_variable

The only think you have jet to do, is to cast your variable to the right date format.

sample:

cast(date_from_variable, smalldate)

1 Comment

-1: This returns all elements that are bigger than the specified variable, no matter whether or not there is a gap in between.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.