0

I've a table like this

ID        col1         col2        col3      col4
---------------------------------------------------
1          a            b           c         d
2          e            f           g         h

So if I pass the ID 2 it should return all the colum values as separate rows as this

Colum     Value
---------------------
ID        2
Col1      e
col2      f
col3      g
col4      h

So all the cells of that single rows been splitted as separate rows.

How can I accomplish this

Sandeep Thomas
  • 4,303
  • 14
  • 61
  • 132

3 Answers3

1

One way to do it with unpivot and union all.

select 'id' as colu,cast(id as varchar(255)) as val from t where id=2
union all
select colu,val
from t
unpivot (val for colu in (col1,col2,col3,col4)) u
where id=2
Vamsi Prabhala
  • 48,685
  • 4
  • 36
  • 58
0

You can use cross apply as below:

Select Id as [Column], [Value]  from yourcols
    cross apply (values(col1), (col2), (col3), (col4)) rws([Value])
    where Id = 2
Kannan Kandasamy
  • 13,405
  • 3
  • 25
  • 38
-1

Please refer the below stack over flow link SQL query to split column data into rows

found the question identical as yours.