SQL statement I wrote (delete category, update number)

Source: Internet
Author: User

Today, I wrote a complex SQL statement. The result shows that it does not meet the project requirements, but the syntax is worth learning.

  1. Declare @ delid int -- the row to be deleted
  2. Declare @ CID int
  3. Set @ delid = '000000'
  4. Begin transaction T1
  5. Delete from ttest where Unit No. = @ delid
  6. Declare mycur cursor for select ID from ttest where convert (INT, unit number)> convert (INT, @ delid)
  7. Open mycur
  8. Fetch next from mycur into @ CID -- similar to datareader. Read (), move down
  9. While (@ fetch_status = 0) -- similar to datareader. Read ()
  10. Begin -- processing logic here
  11. Update ttest set unit number = '00' + convert (varchar (20), convert (INT, unit number)-1) Where id = @ CID
  12. Fetch next from mycur into @ CID -- start a new round of loop. If this is missing, it becomes an endless loop.
  13. End
  14. Close mycur
  15. Deallocate mycur
  16. Commit

My data table is ttest.

Id int Unit No. varchar (20)

2 001001

3 001002

4 001003

5 001004

6 001005

7 001006

The business logic I want to implement is:

If you delete a row, such as 001002

The updated row number is greater than 001002, that is, the number is reduced by 1.

That is, keep the numbers neatly.

 

The problem I didn't consider was that when I updated other rows, other rows were associated with many tables.

Therefore, other rows cannot be updated during deletion.

In addition, find the smallest number to be deleted and add it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.