Click here to Skip to main content
15,906,106 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i have the following procedure, when i execute the procedure. it always give me the error "Incorrect syntax near AND". I dont have idea on what is wrong with it. I have gone through many times the codes and cant find what is the error. Below are my procedure:

SQL
<pre lang="sql">DECLARE @SQL NVARCHAR(MAX)
DECLARE @params NVARCHAR(MAX)

SELECT @SQL = 'SELECT CustomerName,[0] as Pending, [1] as Save_As_Draft, [2] as Spec_Confirmed, [3] as Request_Revision, [4] as Withdraw, [5] as Pending_RND, [6] as Pending_QC, [7] as Manday_Confirmed, [0]+[1]+[2]+[3]+[4]+[5]+[6]+[7] as Total
FROM
(
    SELECT P.DocStatus,C.CustomerName,P.CustomerID
    FROM dbo.CRF_Project P
    INNER JOIN dbo.CustomerList C
    ON P.CustomerID = C.CustomerID
    WHERE Year([CreateDate])= '+@YEAR+'
) p

PIVOT
(
    COUNT (CustomerID) FOR DocStatus IN ([0], [1], [2], [3], [4], [5], [6], [7])

) AS pvt '

SELECT @params = '@CUSTNAME VARCHAR(MAX),
                  @YEAR VARCHAR(MAX)'

IF(@CUSTNAME != '')
    SELECT @SQL = @SQL + ' AND CustomerName IN (' + @CUSTNAME + ')'
ELSE
    SELECT @SQL = @SQL

EXEC sp_executesql @SQL, @params, @CUSTNAME, @YEAR
END
Posted
Updated 3-Jun-14 15:35pm
v2

1 solution

simply change the
SQL
' AND CustomerName IN (' + @CUSTNAME + ')'
into
SQL
' WHERE CustomerName IN (' + @CUSTNAME + ')'


as in the
SQL
SELECT @SQL = @SQL + ' AND CustomerName IN (' + @CUSTNAME + ')'


the SQL Server will combine the @SQL with the new AND statement behind. Therefore the AND statement is not append behind the WHERE inside the pivot but after the pivot p. Instead of using AND, WHERE should be used.
 
Share this answer
 
Comments
DamithSL 3-Jun-14 22:40pm    
my 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



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