SQL SERVER行转列存储过程

CREATE PROCEDURE proc_RowToColumn(
  @TabName sysname,
  @PivotCol sysname,
  @PivotValue sysname,
  @group nvarchar(4000)
)
AS
EXEC('
declare @s nvarchar(4000)
set @s=''''
Select   @s=@s+'',''+quotename(['+@PivotCol+'])+''=max(case when ['+@PivotCol+']=N''+quotename(['+@PivotCol+'],'''''''')+'' then ['+@PivotValue+'] else 0 end)''
from ['+@TabName+'] group by ['+@PivotCol+']
exec(''select ['+@group+']''+@s+'' from ['+@TabName+'] group by ['+@group+']'')
')

GO

你可能感兴趣的:(SQL SERVER行转列存储过程)