SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS OFF GO CREATE PROCEDURE [dbo].[SimpleXTab] @XField varChar(20), @XTable varChar(20), @XWhereString varChar(250), @XFunction varChar(10), @XFunctionField varChar(20), @XRow varchar(40) AS Declare @SqlStr nvarchar(4000) Declare @tempsql nvarchar(4000) Declare @SqlStrCur nvarchar(4000) Declare @col nvarchar(100) set @SqlStrCur = N'Select [' + @XField + '] into ##temptbl_Cursor from [' + @XTable + '] ' + @XWhereString + ' Group By [' + @XField + ']' /* select @sqlstrcur */ exec sp_executesql @sqlstrcur declare xcursor Cursor for Select * from ##temptbl_Cursor open xcursor Fetch next from xcursor into @Col While @@Fetch_Status = 0 Begin set @Sqlstr = @Sqlstr + ", " set @tempsql = isnull(@sqlstr,'') + isnull(@XFunction + '( Case When ' + @XField + " = '" +@Col + "' then [" + @XFunctionField + "] Else 0 End) As [" + @XFunction + @Col + "]" ,'') set @Sqlstr = @tempsql Fetch next from xcursor into @Col End /* Select @Sqlstr as [mk], len(@sqlstr) as [leng] */ set @tempsql = 'Select ' + @XRow + ', ' + @Sqlstr + ' From ' + @XTable + @XWhereString + ' Group by ' + @XRow set @Sqlstr = @tempsql Close xcursor Deallocate xcursor set @tempsql = N'Drop Table ##temptbl_Cursor' exec sp_executesql @tempsql /* Select @Sqlstr as [mk], len(@sqlstr) as [leng] */ exec sp_executesql @Sqlstr GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO