Solved

Dynamic Crosstab query in SQL Server 2005

Posted on 2010-09-10
6
477 Views
Last Modified: 2012-05-10
I'm trying to create a dynamic crosstab query in server 2005. I copied this codes from a book and modified it to my purpose, but I couldn't get it to work. I got the error saying "The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. My crosstab columns is a datetime field. Here's is the codes, please help:

DECLARE @XColumns NVARCHAR(1024)
SET @XColumns = ''

SELECT @XColumns = @XColumns + [a].[Column] + ', '
      FROM
            (SELECT DISTINCT [Date] AS [Column]
                  FROM TRP.CAP_PHID) AS a

PRINT @XColumns
SET @XColumns = Left(@XColumns, LEN(@XColumns) - 1)

SET @XColumns = 'SELECT Tab, PhID, ProdLine, Segment, '
      + @XColumns
      + ' FROM TRP.CAP_PHID PIVOT (SUM (FullProj) FOR [Date] IN ('
      + @XColumns
      + ')) AS pt'
PRINT @XColumns

EXEC sp_executesql @XColumns
0
Comment
Question by:HNA071252
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 41

Accepted Solution

by:
ralmada earned 500 total points
ID: 33649813
may I suggest this code instead?

DECLARE @strSQL VARCHAR(MAX) 
DECLARE @COLS NVARCHAR(2000) 
  
SELECT @COLS = STUFF((SELECT  distinct
                                        '], [' + convert(varchar, [Date], 112)
                                FROM TRP.CAP_PHID order by 1
                                FOR XML PATH('') 
                                ), 1, 2, '') + ']' 


set @strSQL = 'SELECT Tab, PhID, ProdLine, Segment, ' + @Cols
      + ' FROM TRP.CAP_PHID 
	  PIVOT (SUM (FullProj) FOR [Date] IN (' + @Cols + ')) AS pt'


EXEC sp_executesql @strSQL

Open in new window

0
 

Expert Comment

by:A071252
ID: 33650278
How do I use this code? I executed in the SQL Server window and I got this message:
Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'.
0
 
LVL 41

Assisted Solution

by:ralmada
ralmada earned 500 total points
ID: 33650354
just add N' there

DECLARE @strSQL NVARCHAR(MAX) 
DECLARE @COLS NVARCHAR(2000) 
  
SELECT @COLS = STUFF((SELECT  distinct
                                        '], [' + convert(varchar, [Date], 112)
                                FROM TRP.CAP_PHID order by 1
                                FOR XML PATH('') 
                                ), 1, 2, '') + ']' 


set @strSQL = N'SELECT Tab, PhID, ProdLine, Segment, ' + @Cols
      + N' FROM TRP.CAP_PHID 
	  PIVOT (SUM (FullProj) FOR [Date] IN (' + @Cols + N')) AS pt'


EXEC sp_executesql @strSQL

Open in new window

0
Do you have a plan for Continuity?

It's inevitable. People leave organizations creating a gap in your service. That's where Percona comes in.

See how Pepper.com relies on Percona to:
-Manage their database
-Guarantee data safety and protection
-Provide database expertise that is available for any situation

 

Expert Comment

by:A071252
ID: 33650434
Great! It works. How do I change to show the column as "200901" (instead of 20090101, etc.)? Also how do I put this into a view so that I could link to it from Access?
0
 
LVL 41

Assisted Solution

by:ralmada
ralmada earned 500 total points
ID: 33650507
>>Also how do I put this into a view so that I could link to it from Access? <<
you can't.
What you will need to to is create a stored procedure and call the SP from access.
>>How do I change to show the column as "200901" (instead of 20090101, etc.)?  <<
So you just want to show the month and not all days? Try the below:

DECLARE @strSQL NVARCHAR(MAX) 
DECLARE @COLS NVARCHAR(2000) 
  
SELECT @COLS = STUFF((SELECT  distinct
                                        '], [' + convert(varchar(6), [Date], 112)
                                FROM TRP.CAP_PHID order by 1
                                FOR XML PATH('') 
                                ), 1, 2, '') + ']' 


set @strSQL = N'SELECT Tab, PhID, ProdLine, Segment, ' + @Cols
      + N' FROM (SELECT *, convert(varchar(6), [Date]) as dat TRP.CAP_PHID ) o
	  PIVOT (SUM (FullProj) FOR dat IN (' + @Cols + N')) AS pt'


EXEC sp_executesql @strSQL

Open in new window

0
 

Author Closing Comment

by:HNA071252
ID: 33650717
Great help, Thank you very much!
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many companies are making the switch from Microsoft to Google Apps (https://www.google.com/work/apps/business/). Use this article to learn more about what Google Apps has to offer and to help if you’re planning on migrating to Google Apps. It is …
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
The viewer will learn how to simulate a series of sales calls dependent on a single skill level and learn how to simulate a series of sales calls dependent on two skill levels. Simulating Independent Sales Calls: Enter .75 into cell C2 – “skill leve…
The viewer will learn how to use the =DISCRINV command to create a discrete random variable, use this command to model a set of probabilities and outcomes in a Monte Carlo simulation, and learn how to find the standard deviation of a set of probabil…

622 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question