How to write a query so that each column of table1 separated by comma Without including each column name
+------+-----+-----------+-------------+
| eno |dno | ename | job_type |
+------+-----+-----------+-------------+
| 101 | 1 | sam | manager |
| 102 | 2 | ash | teacher |
| 103 | 3 | rohan | clerk |
| 104 | 4 | sohan | peon |
| 105 | 5 | mohan | guar |
+------+-----+------------+------------+
I want to output like this
101,1,sam,manager
102,2,ash,teacher
And rest are same
With the help of a CROSS APPLY (or two), a little XML and STUFF()
A word of caution: This approach will EXCLUDE NULL values
Declare @YourTable table (eno int,dno int, ename varchar(25),job_type varchar(25))
Insert Into @YourTable values
(101,1,'sam' , 'manager'),
(102,2,'ash' , 'teacher'),
(103,3,'rohan', 'clerk' ),
(104,4,'sohan', 'peon' ),
(105,5,'mohan', 'guar' )
Select C.*
From @YourTable A
Cross Apply (Select XMLData=cast((Select A.* for XML Raw) as xml)) B
Cross Apply (
Select String=Stuff((Select ',' +Value
From (
Select Value = attr.value('.','varchar(max)')
From XMLData.nodes('/row') as A(r)
Cross Apply A.r.nodes('./@*') AS B(attr)
) X
For XML Path ('')),1,1,'')
) C
Returns
String
101,1,sam,manager
102,2,ash,teacher
103,3,rohan,clerk
104,4,sohan,peon
105,5,mohan,guar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With