我的表格值为
FKTABLE_NAME FKCOLUMN_NAME PKCOLUMN_NAME
table1 column1 column1
table1 column2 column2
table2 column1 column1
table2 column2 column2
我需要如何将其转换为
FKTABLE_NAME FKCOLUMN_NAME PKCOLUMN_NAME
tablel1 column1,column2 column1,column2
table12 column1,column2 column1,column2
基本上,我试图通过表名来获取逗号分隔列组。
感谢
答案 0 :(得分:3)
这是任何db
的工作查询select distinct table_name,
stuff((select ','+data_type
from information_schema.columns b
where b.table_name=a.table_name
for xml path(''),type).value('.[1]','nvarchar(max)'),1,1,'') AS data_types,
stuff((select ','+column_name
from information_schema.columns b
where b.table_name=a.table_name
for xml path(''),type).value('.[1]','nvarchar(max)'),1,1,'') AS column_names
from information_schema.columns a
这是您的查询
select distinct FKTABLE_NAME,
stuff((select ','+FKCOLUMN_NAME
from tbl b
where b.FKTABLE_NAME=a.FKTABLE_NAME
for xml path(''),type).value('.[1]','nvarchar(max)'),1,1,'') AS FKCOLUMN_NAMES,
stuff((select ','+PKCOLUMN_NAME
from tbl b
where b.FKTABLE_NAME=a.FKTABLE_NAME
for xml path(''),type).value('.[1]','nvarchar(max)'),1,1,'') AS PKCOLUMN_NAMES
from tbl a
答案 1 :(得分:0)
SELECT [Col1Name] + ',' + [Col2Name] + ',' ... + [ColNName]
FROM [tableName]
答案 2 :(得分:0)
与所有字符串聚合问题一样,我建议编写一个自定义聚合(我强烈建议使用clr聚合以获得最佳性能)并编写一个这样的查询
select fktablename, stringAggregate(fkcolumnname), stringAggregate(pkcolumnname)
group by
fktablename
答案 3 :(得分:0)
下面的SQL语句用于转换单行中的单列数据:
declare @testdata varchar(8000)
set @testdata=''
select @testdata=@testdata+NAME+', ' from User where ID in('1','2','3','4','5')
print @testdata
select substring(@testdata,0,len(@testdata))
在上面的例子中:
供参考,请参阅以下链接:
http://www.thedevheaven.com/2012/02/column-data-in-to-single-row-with-comma.html