Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 SQLteam Crosstab proc ordering of the pivot column

Author  Topic 

sqlchiq
Posting Yak Master

133 Posts

Posted - 2008-08-13 : 14:55:37
here's the code


USE [Connotate]
GO
/****** Object: StoredProcedure [dbo].[crosstab] Script Date: 08/13/2008 11:50:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[crosstab]
@select varchar(8000),
@sumfunc varchar(100),
@pivot varchar(100),
@table varchar(100)
AS

DECLARE @sql varchar(8000), @delim varchar(1)
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

EXEC ('SELECT ' + @pivot + ' AS [pivot] INTO ##pivot FROM ' + @table + ' WHERE 1=2')
EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @pivot + ' FROM ' + @table + ' WHERE '
+ @pivot + ' Is Not Null')

SELECT @sql='', @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )

SELECT @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) )
WHEN 0 THEN '' ELSE '''' END
FROM tempdb.information_schema.columns
WHERE table_name='##pivot' AND column_name='pivot'

SELECT @sql=@sql + '''' + convert(varchar(100), [pivot]) + ''' = ' +
stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN '
+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN ' ) + ', ' FROM ##pivot

DROP TABLE ##pivot

SELECT @sql=left(@sql, len(@sql)-1)
SELECT @select=stuff(@select, charindex(' FROM ', @select)+1, 0, ', ' + @sql + ' ')

EXEC (@select)
SET ANSI_WARNINGS ON




It executes fine, the only thing is that the pivot column,

isn't displayed in order.

for example I have shipnames on the 1st column, and then across the top I have the saildates, but instead of


07/01/2008 07/03/2008 07/10/2008 07/17/2008 07/24/2008 08/12/2008

it displays it as


07/24/2008 07/10/2008 07/17/2008 08/12/2008 07/01/2008 07/03/2008


Is there anyway to order this guy?

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-08-14 : 05:45:27
Before EXEC(@select) add this

SELECT @select=@select+ ' ORDER BY 2')

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -