Click here to Skip to main content
15,891,828 members

PIVOT Error = Incorrect syntax near '('.

tonydsouza1987 asked:

Open original thread
The below query gives the error as rrect syntax near '('. :
Can you please help me where I am wrong?
SELECT DDate,COALESCE([February],0) AS [February], COALESCE([August],0) AS [August], COALESCE([April],0) AS [April], COALESCE([December],0) AS [December], COALESCE([September],0) AS [September], COALESCE([January],0) AS [January], COALESCE([October],0) AS [October] FROM
( select DATENAME(month,dbo.ConvertIntToDate(Date_)) as DDate,Amount1 from data where code=1257 
) as SourceTable
PIVOT 
( 
sum(Amount1) 
FOR DATENAME(month,dbo.ConvertIntToDate(Date_)) as DDate IN([February],[August],[April],[December],[September],[January],[October])
)


The original query is as below, the above is the print command results of dynamic query.
Original query:
SQL
DECLARE @MONTHS NVARCHAR(MAX),@MONTHSIN NVARCHAR(MAX)
SELECT @MONTHS = STUFF((select ',' + quotename(DDate) 
FROM (select distinct DATENAME(mm,dbo.ConvertIntToDate(Date_)) as DDate from data) X FOR XML PATH('')) ,1,1,'')

SELECT @MONTHSIN= STUFF((select ', COALESCE(' + quotename(DDate)+ ',0) AS ' + quotename(DDate) 
FROM   (select distinct DATENAME(mm,dbo.ConvertIntToDate(Date_)) as DDate from data) X FOR XML PATH('') ),1,2,'')

SELECT @MONTHS = SUBSTRING(@MONTHS,1,LEN(@MONTHS)-1)
 print @MONTHS;
DECLARE @SQLSTR NVARCHAR(MAX)
SELECT @SQLSTR = 
'SELECT DDate,'+ @MONTHSIN + ' FROM
( select DATENAME(month,dbo.ConvertIntToDate(Date_)) as DDate,Amount1 from data where code=1257 
) as SourceTable
PIVOT 
( 
sum(Amount1) 
FOR DATENAME(month,dbo.ConvertIntToDate(Date_)) as DDate IN(' + @MONTHS + ')
)'
print @SQLSTR
execute @SQLSTR
--'PRINT @MONTHS;

I want to pivot the data month wise. Please can anybody help me with this. The months should be generated dynamic based on the data in the table 'data'. Thank you.
Tags: SQL, T-SQL, SQL Server 2005, SQL Server, SQL Server 2008

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900