I have a sample table you can see below:
CREATE TABLE [dbo].[Assets](
[id] [int] IDENTITY(1,1) NOT NULL,
[Part] [nvarchar](500) NOT NULL,
[ParentId] [int] NULL,
CONSTRAINT [PK_Assets] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_Assets_ParentId] ON [dbo].[Assets]
(
[ParentId] ASC
)WITH (PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF,
DROP_EXISTING = OFF,
ONLINE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
set identity_insert [dbo].[Assets] on;
insert into dbo.Assets ([id], [ParentId], [Part]) values
(1 ,null, 'HeaterAsset'),
(2 ,5,'Motor'),
(3 ,1,'Body'),
(4 ,2,'Coil'),
(5 ,1,'GearBox'),
(6 ,2,'Shaft'),
(7 ,5,'Gears'),
(8 ,null, 'FanAsset'),
(9 ,8,'Body'),
(10 ,9,'Fance'),
(11 ,8,'Motor'),
(12 ,11,'Coil'),
(13 ,11,'Shaft')
set identity_insert [dbo].[Assets] off;
I want to write a SQL Query to create a Json result containing a hierarchal top-down representation of each asset. Please help me. I'm new to SQL and I want to learn recursion by studying your code. Thanks.