FAQ, give a record ID, find out all its parents up to the top level
Use SMSS, sql server, find a way.
The idea is to divide into two steps, first loop to find the IDs of all the parents, and then use IN to find out all the parents
Column Description ID=PK ParentId = Parent ID ParentId = 0 means to the top level
SQL statement:
DECLARE @childrenId VARCHAR (32) -- To find all parents of this ID
DECLARE @1parentIds VARCHAR (max) -- The ID list of all parents, and finally spell the condition of IN. The effect is: '111','222' ,'333'
SET @1parentIds = ''''+@childrenId+'''' -- also includes itself, all the way to the parent
WHILE @childrenId!='0' -- If the parent ID is not 0, continue to find
BEGIN
SELECT @childrenId = ParentId FROM [table] WHERE Id=@childrenId -- Find the record according to the ID, assign its parent ID to the value, this The parent ID is used as the child ID of the next level to find
SET @1parentIds= @1parentIds + ',' + '''' + @childrenId + '''' -- splicing this parent ID
END
-- Since the concatenated string cannot be used as the parameter of IN, I think of this method to spell the entire SQL and execute it.
EXEC('SELECT * FROM [table] WHERE Id IN (' + @1parentIds + ')'+'ORDER by Id')