Here's a query that returns the count of all the characters. Assming your table is called 'Products'
WITH ProductChars(aChar, remain) AS (
SELECT LEFT(productName,1), RIGHT(productName, LEN(productName)-1)
FROM Products WHERE LEN(productName)>0
UNION ALL
SELECT LEFT(remain,1), RIGHT(remain, LEN(remain)-1) FROM ProductChars
WHERE LEN(remain)>0
)
SELECT aChar, COUNT(*) FROM ProductChars
GROUP BY aChar
This query returns each character as a separate row, along with the number of occurrences. To combine them all to a single row, (as stated in the question), change the final SELECT
to
SELECT aChar AS [text()] FROM
(SELECT DISTINCT aChar FROM ProductChars) base
FOR XML PATH('')
(That uses a nice hack I found here, which emulates the GROUP_CONCAT
from MySQL.)
The first level of recursion is unrolled so that the query doesn't return empty strings in the output.