SQL statement Recursion Algorithm

Source: Internet
Author: User

The table structure is as follows:

Department superior department
A B
B c
C d
A
B
C

Find an SQL statement and check its superior department according to A. the query result is
Superior department
B
C
D

========================================================== ==========

Functions
Create Table Tb (Department varchar (20), higher-level department varchar (20 ))

Insert into TB select 'A', 'B' Union all select 'B', 'C' Union all select 'C', 'D'
Union all select 'A', 'A' Union all select 'B', 'B' Union all select 'C', 'C'

-- Select * from TB
Create Function test_f (@ name varchar (20 ))
Returns @ ta table (superior department varchar (20 ))
As
Begin
-- Select @ name = superior department from TB where Department = @ name and department! = Superior department
While exists (select 1 from TB where Department = @ name and department! = Higher-level department)
Begin
Insert @ ta select superior department from TB where Department = @ name and department! = Superior department
Select @ name = superior department from TB where Department = @ name and department! = Superior department
End
Return
End

Select * From DBO. test_f ('A ')

Delete:
Drop function test_f
Drop table TB

Superior department
--------------------
B
C
D

(The number of affected rows is 3)

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.