--SQL SERVER 2000 的存储过程 你自己修改一下
Create procedure TestProc
as
begin
declare @SqlText varchar(8000), @TmpSql varchar(7000)
declare @TmpTable table(ID int identity(1,1), [month] int)
insert into @TmpTable([month]) select DISTINCT [month] from TbSalery order by [month]
declare @MID int, @MCount int, @MValue varchar(10)
select @MCount = count(1), @MID = 1 from @TmpTable
set @TmpSql = ''
while @MID <= @MCount
begin
select @MValue = [month] from @TmpTable where ID = @MID
if @MID <> @MCount
set @TmpSql = @TmpSql + 'sum(case when [month] = ' + @MValue + ' then Salery else 0 end) ' + '[' + @MValue + '] ' + ' ,' + char(13)
else
set @TmpSql = @TmpSql + 'sum(case when [month] = ' + @MValue + ' then Salery else 0 end) ' + '[' + @MValue + '] ' + char(13)
set @MID = @MID + 1
end
set @SqlText = 'select name, ' + char(13) + @TmpSql + char(13) + 'from TbSalery group by name'
--print @SqlText
exec(@SqlText)
end