SqlServer database of recursive

Recursion is relatively simple to achieve, here is directly attached to the SQL.

- simply create a user table 
the CREATE  TABLE   the User ( 
     UserID INT  PRIMARY  KEY  IDENTITY ( 1 , 1 ), 
     ParentUserID INT   
)

This assumption that there are thousands of pieces of data, it began recursion.

WITH cte AS
(
    SELECT a.UserID,0 AS lvl FROM [User] a WHERE a.ParentUserID=@UserID
    UNION ALL
    SELECT a.UserID,1+lvl FROM [User] a INNER JOIN cte c ON a.ParentUserID =c.UserID
)
SELECT * INTO #Temp FROM cte

Adding to the temporary table, a recursive query results

Recursive efficiency is very high!

Guess you like

Origin www.cnblogs.com/nnnnnn/p/10948309.html