首页 > 代码库 > 行变列 拼接字符串 MSSQL 一个超级搞的问题

行变列 拼接字符串 MSSQL 一个超级搞的问题

由数据ThreeLevelSortID KeyWordID   KeyWordName2             142         key12             142         key23             143         key33             144         key4得到数据大ThreeLevelSortID KeyWordName2                key1,key23                key3,key4declare @tblTmp table (id int,ThreeLevelSortID int,KeyWordName nvarchar(max))declare @tblTmpCount intinsert @tblTmp(id,ThreeLevelSortID)select ROW_NUMBER() over (order by t.ThreeLevelSortID), t.ThreeLevelSortID from ( select Distinct ThreeLevelSortID from tbl_ThreeLevelSortKeyWordsDetail) tselect @tblTmpCount = count(1) from @tblTmpdeclare @index intset @index = 0While(@index<)begindeclare @currentThreeLevelSortID intselect @currentThreeLevelSortID = ThreeLevelSortIDfrom @tblTmp where id = @index--拼接关键词字符串declare @keywords nvarchar(max)select @keywords=ISNULL(@keywords+;,‘‘)+k.KeyWordName from (SELECT h.KeyWordID,h.ThreeLevelSortID,j.KeyWordName FROM dbo.tbl_ThreeLevelSortKeyWordsDetail h,dbo.tbl_KeyWords jWHERE ThreeLevelSortID = @currentThreeLevelSortIDAND h.KeyWordID = j.KeyWordID) kupdate @tblTmp set KeyWordName = @keywords where ThreeLevelSortID = @currentThreeLevelSortIDset @keywords = nullset @index = @index +1endselect * from @tblTmp求简单方法

 

行变列 拼接字符串 MSSQL 一个超级搞的问题