Bom creates user-defined functions, and the information of each sub-node de parent node

Source: Internet
Author: User
-- Generate Test Data
Create Table BOM (ID int, parentid int, sclassname varchar (10 ))
Insert into BOM values (1111, '123 ')
Insert into BOM values (1111, '2017 _ 1 ')
Insert into BOM values (1111, '2014-1-1 ')
Insert into BOM values (1111, '2017-1-1-1 ')
Insert into BOM values (1111, '1970-2 ')

Go

-- Create a user-defined function. The information of each sub-node de parent node
Create Function f_getparent (@ id int)
Returns varchar (40)
As
Begin
Declare @ RET varchar (40)

While exists (select 1 from BOM where id = @ ID and parentid <> 0)
Begin
Select @ ID = B. ID, @ ret = ',' + rtrim (B. ID) + isnull (@ ret ,'')
From
Bom A and Bom B
Where
A. ID = @ ID and B. ID = A. parentid
End

Set @ ret = stuff (@ ret, 1, 1 ,'')
Return @ RET
End
Go

-- Execute Query
Select ID, isnull (DBO. f_getparent (ID), '') as parentid from BOM
Go

-- Output result
/*
Id parentid
---------------------------------------------------
1
2 1
3 1, 2
4 1, 2, 3
5 1
*/

-- Delete test data
Drop function f_getparent
Drop table BOM
Go

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.