SQL Server with a recursive delete

Source: Internet
Author: User

A common table expression (CTE) is provided in Server 2005, using a CTE to make the SQL statement maintainable, while the CTE is much more efficient than a table variable.

Stored Procedure methods:

1Create proc Up_delete_nclass
2@ didInt
3As
4With My1 as (SELECT * from news_class where id = @ did
5UNION ALL select news_class.* from My1, news_class where my1.id = News_class.parentid
6)
7Delete from News_class where exists (select ID from my1 where my1.id = news_class.id)
8Go
9
TenEXEC Up_delete_nclass -

Non-Stored procedure method:

1With My1 as (SELECT * from AAA WHERE id =1
2UNION ALL select Aaa.* from My1, aaa where my1.id = Aaa.pid
3)
4Delete from the AAA where exists (select ID from my1 where my1.id = aaa.id)

Related Article

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.