如何编写查询以逗号分隔每列而不指定每个列名

时间:2017-03-03 14:53:21

标签: sql sql-server sql-server-2008

如何编写查询以使table1的每一列用逗号分隔 不包括每个列名

+------+-----+-----------+-------------+
| 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        |
+------+-----+------------+------------+

我想像这样输出

101,1,sam,manager      
102,2,ash,teacher

休息是一样的

2 个答案:

答案 0 :(得分:2)

借助CROSS APPLY(或两个),一点XML和STUFF()

  

提醒一句:此方法将排除空值

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

<强>返回

String
101,1,sam,manager
102,2,ash,teacher
103,3,rohan,clerk
104,4,sohan,peon
105,5,mohan,guar

答案 1 :(得分:0)

您也可以使用动态SQL查询来执行此操作。

<强>查询

declare @sql as varchar(max);

select @sql = 'select case when right(t.csv, 1) = ' + char(39) + ',' + char(39) 
            + ' then left(t.csv, len(t.csv) - 1) else t.csv end as csv from(select ' 

            + stuff((select '+ case when [' + column_name + '] is null then ' 
            + char(39) + char(39) +
      ' else cast(['  + column_name + '] as varchar(max)) + ' 
            + char(39) + ',' + char(39) + ' end'
            from information_schema.columns
            where table_name = 'dds_emp'
            order by ordinal_position asc
            for xml path('')
        ), 1, 1, '');

select @sql += ' as csv from dds_emp)t;';
exec(@sql);