database table Looping

Source: Internet
Author: User

There are two fields in a table: Orgid,parentorgid. OrgID is the primary key, Parentorgid is the parent unit OrgID. The requirements came, which now need an infinite recursion based on any one of the orgid values of the current table to isolate it subordinate to all orgid.

BEGIN
DECLARE @ParentOrgID VARCHAR (32); --Parent Organization ID
CREATE Table #TempBase_Org--Temporary main table
(
OrgID VARCHAR (32)
)
Insert #TempBase_Org Select OrgID from dbo. base_org where [email protected] --Identify the current child section ID according to the parent Parentorgid and insert the temporary table.
While @ @rowcount <>0-This is the most critical, loop-recursive call.
BEGIN
Insert #TempBase_Org Select A.orgid from base_org a
INNER JOIN #TempBase_Org B on A.parentorgid=b.orgid and
Not EXISTS (select 1 from #TempBase_Org where Orgid=a.orgid)
END
INSERT into #TempBase_Org VALUES (@ParentOrgID); --Insert the ancestor ID into the temporary table.
END

The above is the main SQL statement.

database table Looping

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.