1

Can someone tell me how to do this as a loop in SQL?

update Bank set Report_date_next='2014-02-28' where Reporting_date='2014-01-31'
update Bank set Report_date_next='2014-03-31' where Reporting_date='2014-02-28'
update Bank set Report_date_next='2014-04-30' where Reporting_date='2014-03-31'
update Bank set Report_date_next='2014-05-31' where Reporting_date='2014-04-30'
update Bank set Report_date_next='2014-06-30' where Reporting_date='2014-05-31'
update Bank set Report_date_next='2014-07-31' where Reporting_date='2014-06-30'

The list goes on for quite a while so I need a counter on how to find the last cell as well similar to the XlDown in VBA.

1

1 Answer 1

2

You're way better off using a CASE statement:

UPDATE Bank
SET Report_date_next = CASE WHEN Reporting_date = '2014-01-31' THEN '2014-02-28'
                            WHEN Reporting_date = '2014-02-28' THEN '2014-03-31'
                            WHEN ...etc
                        END

If you tag your question with the DBMS you're using, there may be an even easier way depending on the functions available to you.

For instance, SQL Server 2012+ you can do:

UPDATE Bank
SET report_date_next = EOMONTH(Reporting_date,1)
Sign up to request clarification or add additional context in comments.

1 Comment

@SergeKashlik NP, I was able to simplify it a bit farther too. The DATEADD was unnecessary

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.