Click here to Skip to main content
15,919,358 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
row
1
1
1
2
2


now I want to insert this to another table like this

col1 col2 col3 col4 col5
1 1 1 2 2

and then replace 1 --->Y and 2-->N

What I have tried:

SELECT col1, col2, col3, col4,col5,col6,col7,col8,col9,col10,col11,col12,col13,col14,col15
FROM (
select * from Split('1:1:1:1:1:1:2:2:1:2:1:1:2:1:1:',':')
) Books
PIVOT (
FOR select * from Split('1:1:1:1:1:1:2:2:1:2:1:1:2:1:1:',':') IN (col1, col2, col3, col4,col5,col6,col7,col8,col9,col10,col11,col12,col13,col14,col15)
) Result;
Posted
Updated 10-Jun-16 1:11am

1 solution

try the below,
/*
;WITH CTE
AS
(
SELECT 1 AS RW UNION ALL
SELECT 1 AS RW UNION ALL
SELECT 1 AS RW UNION ALL
SELECT 2 AS RW UNION ALL
SELECT 2 AS RW
)
SELECT * INTO #A FROM CTE
*/
Insert your result set into #A temp table (RW - column name)
SELECT * FROM #A

Then execute the below,

ALTER TABLE #A ADD ID INT IDENTITY(1,1)
ALTER TABLE #A ADD CN VARCHAR(10)

UPDATE #A SET CN = 'Col' + CAST(ID AS VARCHAR(10))

DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(CN)
from #A
group by CN, id
order by id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')

set @query = 'SELECT ' + @cols + ' from
(
select CASE WHEN RW = 1 THEN '+CHAR(39)+'Y'+CHAR(39)+' ELSE '+CHAR(39)+'N'+CHAR(39)+' END AS RW, CN
from #A
) x
pivot
(
max(RW)
for CN in (' + @cols + ')
) p '

execute(@query)
 
Share this answer
 
Comments
kumari567 14-Jun-16 6:14am    
this is too complicated ..i m not able to understand this
kumari567 22-Jun-16 0:52am    
how many columns are in #A
kumari567 22-Jun-16 1:39am    
please see this link and if possible then provide some solution
http://www.codeproject.com/Questions/1107889/How-to-convert-a-column-separated-value-into-diffe

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900