The so-called tree structure of the relationship, that is, records have id,parentid relationship between the data. The scenario is this: the business uses a sharing table, the main field of the list has the share person, and the person to be shared, as well as share the task ID, can be constructed through a series of sharing tree-like structure, the requirement is to delete any node, you need to delete all the sharing of the associated data.
Scenario 1: Each node can be used with an identity to connect the shared relationship string together into a character, the table adds a field to record the path string, delete the node when the condition is only the path containing the node relationship record is deleted, this scheme is inspired by the Windows Create folder mode, Each folder corresponds to a unique path, and deleting a folder will delete the associated files.
Scenario 2: Through the trigger, listen to the deletion of the share table, delete the data, the deleted data is shared by the person as a shared query related records, and kill, and so on, recursive delete. However, such an operation can only be recursive operation less than 32 layer, otherwise will be error, and this recursive call performance is not good. But you can learn the use of triggers
ALTER TRIGGER [dbo].[Myfirsttrigger] on [dbo].[sharetable] for DELETE as BEGIN --SET NOCOUNT on; DECLARE @id INT,--share ID; @customer VARCHAR( $), @tocustomer VARCHAR( $), @taskId VARCHAR( -) --SELECT @id=Id@customer=Customer@tocustomer=Tocustomer fromDELETED; DELETE fromDbo. SharetableWHERECustomerinch(SELECTTocustomer fromDELETED)END
Scenario 3: With the CTE recursive, querying the associated data, he does not have recursive hierarchy restrictions, the use of simple and convenient, this scheme for the final determination of the scheme.
The use of CTE has 2 main aspects, 1 is used as a temporary result set, 2 is specifically used for similar recursion
The specific recursive implementation code is as follows:
withsimplerecursive as ( --Basic statement specifies a record SELECTID, customer, Tocustomer fromdbo. SharetableWHERECustomer= 'Share People' andTocustomer= 'people to be shared' andId=1 UNION All --Recursive Statements SELECTp.id, P.customer, P.tocustomer fromdbo. Sharetable PINNER JOINSimplerecursive A onA.tocustomer=P.customer)SELECTId fromSimplerecursive--get all matching IDs
The deletion scheme of relational table in database tree structure