Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write a query to separate each column by comma without specifying each column name

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

like image 749
novice programmer Avatar asked Dec 18 '25 00:12

novice programmer


1 Answers

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
like image 116
John Cappelletti Avatar answered Dec 20 '25 18:12

John Cappelletti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!