日期:2014-05-17 浏览次数:20860 次
ALTER PROCEDURE Usp_Static
@tableName nvarchar(50),
@groupCol nvarchar(50), --分组字段.
@staticCol nvarchar(50), --统计字段.
@showCol nvarchar(50), --表头字段.
@opera nvarchar(50) --聚会函数.
AS
declare @SQL nvarchar(max), @proColumn nvarchar(50) --存储游标执行的列.
execute ('declare curCol cursor for select distinct '+ @showCol+ ' from '+ @tableName+' for read only') --游标.
begin
set nocount on
set @SQL = 'select '+@groupCol+','+@opera+'('+@staticCol+') as ['+@opera+' of '+ @staticCol+']';
open curCol --打开游标.
while(0=0)
Begin
Fetch next from curCol into @proColumn
if(@@fetch_status<>0) break --游标失败.
set @SQL += ','+@opera+'(case '+@showCol+'
when '+@proColumn+' then '+@staticCol+' else null
End) as ['+@proColumn+']'
End
set @SQL += 'from'+ @tableName +'group by'+ @groupCol
execute @SQL
if(@@error <> 0) return @@error --出错.
close curCol
deallocate curCol return 0 --释放游标成功则返回0.
end