Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multilevel Location – Output as delimited series

I have this table with the intention of having multi-levels of locations: Location within a location. Been trying to no avail. Appreciate if any of you can help.

| Location_ID | Location       | Location_ID1 |
| ----------- | -------------- | ------------ |
| 10001       | Warehouse A    |              |
| 10002       | Warehouse B    |              |
| 10003       | Rack A         | 10001        |
| 10004       | Rack B         | 10001        |
| 10005       | Top Shelf      | 10003        |
| 10006       | Bottom Shelf   | 10003        |

I want to select all of the Locations and populate a dropdown list with this value-label pair

|Value        | Label                              |
|-------------|------------------------------------|
|10001        |Warehouse A                         |
|10003        |Warehouse A > Rack A                |
|10005        |Warehouse A > Rack A > Top Shelf    |
|10006        |Warehouse A > Rack A > Bottom Shelf |
|10004        |Warehouse A > Rack B                |
|10002        |Warehouse B                         |

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use an rCTE to iterate through the data here, and also delimit your data with a little concatenation:

SELECT *
INTO dbo.YourTable
FROM (VALUES(10001,'Warehouse A',NULL ),
            (10002,'Warehouse B',NULL ),
            (10003,'Rack A',10001),
            (10004,'Rack B',10001),
            (10005,'Top Shelf',10003),
            (10006,'Bottom Shelf',10003))V(Location_ID,Location,Location_ID1);
GO
WITH rCTE AS(
    SELECT Location_ID,
           Location,
           Location_ID1,
           CONVERT(varchar(500),Location) AS Label
    FROM dbo.YourTable YT
    WHERE Location_ID1 IS NULL
    UNION ALL
    SELECT YT.Location_ID,
           YT.Location,
           YT.Location_ID1,
           CONVERT(varchar(500),r.Label + ' > ' + YT.Location) AS Label
    FROM dbo.YourTable YT
         JOIN rCTE r ON YT.Location_ID1 = r.Location_ID)
SELECT *
FROM rCTe;
GO

DROP TABLE dbo.YourTable
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading