0

I would like to create the equivalent of a FOR loop. I need this in SQL. My goal is to create a new column called Difference which calculates the date difference in days between the end of each row and the beginning of the next row. In essence I need to know if there are any breaks in contracts for each personID. RowID from min to max defines a contract with a specific organisation, such as each new contract with one organisation starts with 1.

My table is:

table

The SQL code I wrote is:

select RowID, start_contract, end_contract from table

open the_cursor

fetch next from the_cursor into @id

while @@FETCH_STATUS = 0
begin 
    select
        DATEDIFF(DAY, (select end_contract from table where RowID = @id-1), 
                      (select start_contract from t where RowID = @id)) AS [Difference]

        if (select RowID from t) = 1
            break
        else 
            continue

    fetch next from the_cursor into @id
end

close the_cursor
deallocate the_cursor

But I get an error:

Cursorfetch: The number of variables declared in the INTO list must match that of selected columns.

Could anybody help me please?

Thank you so much.

1

1 Answer 1

1

Try this:

select DATEDIFF(DAY, T.end_contract T.start_contract) AS [Difference], T.personID
from table T join table TT on TT.personID=t.personID
where TT.rowID = T.rowID + 1
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, self-join works really well. I had to modify the code to add a join by TT.rowID=T.rowID+1 instead of where, but it did the trick.

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.