SQL Server Returns recursive result sets.

Source: Internet
Author: User

There is a recursion in the work that needs to be used in many places. I don't want to define every stored procedure, but the view cannot define variables, so I have to write them as functions.

Create Function [DBO]. [f_getdwdata]
(
@ ID int
)
Returns @ t_level table (ID int, level INT) -- recursively queries all subordinate unit data based on the passed ID.
Begin
Declare @ level int
Set @ level = 0
Insert @ t_level select ID, @ level
From mm_dw
Where id = @ ID
While @ rowcount> 0
Begin
Set @ level = @ LEVEL + 1
Insert @ t_level select a. ID, @ level
From mm_dw A, @ t_level B
Where a. SJID = B. ID
And B. Level = @ level-1
End
Return
End

The call method is simple:

Select * From f_getdwdata (@ ID)

In SQL Server 2000, manual loops are used for recursion.

 

In SQL Server 2005, you can use the following method:

Create Function [DBO]. [f_getdwdata]
(
@ ID int
)
Returns @ t_level table (ID int, level INT) -- recursively queries all subordinate unit data based on the passed ID.

Begin

With Act (ID, SJID)
As
(
Select ID, SJID from rzeam. mm_dw
Where id = @ ID
Union all
Select a. ID, A. SJID
From rzeam. mm_dw A, Act
Where a. SJID = act. ID
)

Insert @ t_level
Select ID, SJID from Act

Return
End

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.