MGM
MGM

Reputation: 65

Print result by merging records in a table

I have a table with name "PrintWord" and column name as col_letter and data in it is as follows:

"col_letter"
S
A
C
H
I
N

I would like to print the o/p from this table as:

SACHIN

Thanks!

Upvotes: 0

Views: 28

Answers (2)

mohan111
mohan111

Reputation: 8865

DECLARE @t table
(

    Name varchar(10)
)
INSERT INTO @t
SELECT 's' UNION ALL
SELECT 'a' UNION ALL
SELECT 'c' UNION ALL
SELECT 'h' UNION ALL
SELECT 'i' UNION ALL
SELECT 'n' 

SELECT DISTINCT
stuff(
(
    SELECT ' '+ [Name] FROM @t  FOR XML PATH('')
),1,1,'') 
FROM (SELECT DISTINCT Name FROM @t ) t

Upvotes: 2

potashin
potashin

Reputation: 44601

There is a hard-coded version :

SELECT col_letter
FROM PrintWord
ORDER BY 
 CASE col_letter
 WHEN 'S' THEN 1
 WHEN 'A' THEN 2
 WHEN 'C' THEN 3
 WHEN 'H' THEN 4
 WHEN 'I' THEN 5
 WHEN 'N' THEN 6
 END
FOR XML PATH('')

You need an ORDER BY clause to guarantee the order of the letters.

Upvotes: 1

Related Questions