1

I want to build uniqueidentifier IDs with comma separated as a string in a T-SQL CTE query:

WITH departmentcte(ID, Name, ParentID, LEVEL, FullPath) AS
( 
    SELECT 
        ID, Name, ParentID, 0 AS LEVEL, 
        CAST(Name AS VARCHAR(1024)) AS FullPath 
    FROM 
        ItemModels 
    WHERE 
        ParentID IS NULL

    UNION ALL  

    SELECT 
        d.ID, d.Name, d.ParentID, departmentcte.LEVEL + 1 AS LEVEL,
        CAST(departmentcte.FullPath + '\' + CAST(d.Name AS VARCHAR(1024)) AS VARCHAR(1024)) AS FullPath  
    FROM 
        ItemModels d
    INNER JOIN 
        departmentcte ON departmentcte.ID = d.ParentID
)
SELECT ID, Name, FullPath  
FROM departmentcte;

It returns this result as expected:

enter image description here

But I would like to get all IDs of a subset like

enter image description here

So I try following query and I am getting the error

Type mismatch between the bind and recursive parts in the "SubIDs" column of the recursive "departmentcte" query.

WITH departmentcte(ID, Name, ParentID, LEVEL, FullPath, SubIDs) AS
( SELECT ID, Name, ParentID, 0 AS LEVEL, CAST(Name AS VARCHAR(1024)) AS FullPath, 
    convert(nvarchar(36), ID) as SubIDs FROM ItemModels WHERE ParentID IS NULL
 UNION ALL  
 SELECT d.ID, d.Name, d.ParentID, departmentcte.LEVEL + 1 AS LEVEL,
      CAST(departmentcte.FullPath + '\' + CAST(d.Name AS VARCHAR(1024)) AS VARCHAR(1024)) AS FullPath,    
      ( ISNULL(departmentcte.SubIDs,'') + '\' + convert(nvarchar(36), d.ID) )  AS SubIDs 
 FROM ItemModels d
      INNER JOIN departmentcte ON departmentcte.ID = d.ParentID)
SELECT ID, FullPath, SubIDs  FROM departmentcte;

As I see SubIDs has nvarchar datatype so where is the problem?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
NoWar
  • 36,338
  • 80
  • 323
  • 498

1 Answers1

2

Thanks to all I found the solution

    WITH departmentcte(ID,ParentID, LEVEL, FullPath, SubIDs) AS
    ( SELECT ID,  ParentID, 0 AS LEVEL, CAST(Name AS VARCHAR(1024)) AS FullPath, convert(varchar(2048), ID) as SubIDs 
        FROM ItemModels WHERE ParentID IS NULL
     UNION ALL  
     SELECT d.ID,  d.ParentID, departmentcte.LEVEL + 1 AS LEVEL, 
          CAST(        departmentcte.FullPath  + ','  + CAST(d.Name AS VARCHAR(1024)) AS VARCHAR(1024)) AS FullPath,      
          CAST( ISNULL(departmentcte.SubIDs,'') + ',' + convert(nvarchar(36), d.ID)  AS VARCHAR(2048))  AS SubIDs 
     FROM ItemModels d INNER JOIN departmentcte ON departmentcte.ID = d.ParentID)

SELECT *  FROM departmentcte;

The idea is to use the same size of varchar/nvarchar in both fields of the UNION ALL. In my case it is varchar(2048)

NoWar
  • 36,338
  • 80
  • 323
  • 498
  • 1
    I was just about to post an answer very similar to this. By the way, next time you ask, please include either a demo link or some sample data. Most people won't be able to help much with the question you asked above. – Tim Biegeleisen Aug 19 '20 at 04:41