Transpose query creates nodes (SQL Server 2008)

2019-08-30 16:05发布

问题:

I finally found the query to execute to get all ids (comma separated) for one content in one row.

Following query did the trick:

You don't need to look at the query because it already does what it should do.

SELECT 
    taxonomy_item_id, 
    SUBSTRING(
      (SELECT ', ' + CAST(taxonomy_id AS varchar) AS Expr1
       FROM taxonomy_item_tbl AS t2
       WHERE (t1.taxonomy_item_id = taxonomy_item_id) AND (taxonomy_language_id = 2067)
       ORDER BY taxonomy_item_id, taxonomy_id FOR XML PATH('')
      ), 1, 1000) AS taxonomy_ids
FROM 
    taxonomy_item_tbl AS t1
WHERE 
    (taxonomy_language_id = 2067) AND (taxonomy_item_id = 180555)
GROUP BY 
    taxonomy_item_id

The only problem is the data result I get:

180555  |   <Expr1>, 404</Expr1><Expr1>, 405</Expr1><Expr1>, 723</Expr1><Expr1>, 1086</Expr1><Expr1>, 1087</Expr1><Expr1>, 1118</Expr1><Expr1>, 1124</Expr1><Expr1>, 1126</Expr1>

I don't need the <Expr1> nodes. Is there a way to delete this? If I delete AS Expr1in the query then it is automatically added back

Thanks

回答1:

If you don't want the <Expr1> - then just don't ask for it!

You have:

(SELECT ', ' + CAST(taxonomy_id AS varchar) AS Expr1

That AS Expr1 causes the <Expr1> to be added - so just don't have that expression there.

Try

SELECT 
    taxonomy_item_id, 
    SUBSTRING(
      (SELECT ', ' + CAST(taxonomy_id AS VARCHAR) 
       FROM dbo.taxonomy_item_tbl AS t2
       WHERE t1.taxonomy_item_id = taxonomy_item_id
       AND taxonomy_language_id = 2067
       ORDER BY taxonomy_item_id, taxonomy_id 
       FOR XML PATH('')
      ), 1, 1000) AS taxonomy_ids
FROM 
    dbo.taxonomy_item_tbl AS t1
WHERE 
    taxonomy_language_id = 2067
    AND taxonomy_item_id = 180555
GROUP BY 
    taxonomy_item_id