Hi,
I've the following SQL Server 2005 table:
CREATE TABLE [dbo].[WOr]( [WO] [varchar](10) NULL, [WO_Parent] [varchar](10) NULL, [WO_Group] [varchar](10) NULL ) ON [PRIMARY]
with these test values:
INSERT INTO [WOr] ([WO] ,[WO_Parent] ,[WO_Group]) VALUES ('2000', NULL, NULL) INSERT INTO [WOr] ([WO] ,[WO_Parent] ,[WO_Group]) VALUES ('2001', '2000', NULL) INSERT INTO [WOr] ([WO] ,[WO_Parent] ,[WO_Group]) VALUES ('2002', '2001', NULL) INSERT INTO [WOr] ([WO] ,[WO_Parent] ,[WO_Group]) VALUES ('2003', '2002', NULL) INSERT INTO [WOr] ([WO] ,[WO_Parent] ,[WO_Group]) VALUES ('5000', NULL, NULL) INSERT INTO [WOr] ([WO] ,[WO_Parent] ,[WO_Group]) VALUES ('5001', '5000', NULL) INSERT INTO [WOr] ([WO] ,[WO_Parent] ,[WO_Group]) VALUES ('5002', '5001', NULL) INSERT INTO [WOr] ([WO] ,[WO_Parent] ,[WO_Group]) VALUES ('5003', '5002', NULL)
I need to updating the WO_group column with the WO value of the first item of the chain of records.
In this sample, a chain begins with the record having WO = 2000. This recors hasn't any parent record. The record having WO = 2001 has the record with WO = 2000 as a parent and so on.
The goal is to update the chain from WO = 2000 to WO = 2003 setting the WO_group = 2000.
I'm trying to use a CTE:
WITH CTE(WO, WO_parent, wo_group, Level) AS ( SELECT WO, WO_parent, wo_group, 0 as Level FROM WOr WHERE WO_Parent IS NULL UNION ALL SELECT W1.WO, W1.WO_parent, w1.wo_group, Level + 1 FROM WOr as W1 INNER JOIN CTE as W2 on W1.WO_parent = W2.WO )
but I can setting the WO_group column only for the records without a parent.
Any suggests to me, please? Thanks