我在下面使用动态SQL创建新列并将其展开,但是[MonthList]
字段是连接的,并且需要以某种方式将其拆分为当前仅在[Monthly Rate]
值[MonthList] = @PivotColumns
1}}名称
当前代码:
Set @SQLQuery =
N'SELECT *
FROM [dbo].[TableA]
PIVOT( sum([Monthly Rate])
FOR [MonthsList] IN (' + @PivotColumns + ')) as P'
EXEC sp_executesql @SQLQuery
感谢您的帮助!
答案 0 :(得分:0)
管理使用Cursor提出答案。如果有人感兴趣,那么:
DECLARE @Q NVARCHAR(4000),
@CName VARCHAR(255)
DECLARE ColCur CURSOR
FOR
SELECT C.name as Column_name
FROM sys.columns C
LEFT JOIN sys.tables t
on C.object_id = t.object_id
WHERE t.name = 'TableA'
OPEN ColCur
FETCH NEXT FROM ColCur INTO @CName
WHILE(@@FETCH_STATUS =0)
BEGIN
SET @Q =
case when @CName like '___''__' then
'UPDATE TableA
SET ['+@CName+'] = [Monthly Rate]
WHERE [MonthsList] like ''%'+replace(@CName,char(39),char(39)+char(39))+'%'''
Else ''
end
--print @q
EXEC sp_executesql @Q
FETCH NEXT FROM ColCur INTO @CName
END
CLOSE ColCur
DEALLOCATE ColCur