Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, i have the following stored procedure. When i run it and i insert my parameters, it would prompt me the error as title above. Below are my codes:

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, YEAR(CreateDate) as createYear
    FROM dbo.CRF_Project P
    INNER JOIN dbo.CustomerList C
    ON P.CustomerID = C.CustomerID
) p

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

) AS pvt '

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

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

EXEC sp_executesql @SQL, @params, @CUSTNAME, @YEAR
END



my input are @CUSTNAME 'Osm' and @YEAR '2014'
Posted
Comments
ArunRajendra 18-Jun-14 5:13am    
CreateDate should belong to at least one of the table (dbo.CRF_Project, dbo.CustomerList).
Jamie888 18-Jun-14 5:18am    
indeed, it is belongs to dbo.CRF_Project

"indeed, it is belongs to dbo.CRF_Project"
So tell SQL that:
SQL
SELECT P.DocStatus,C.CustomerName,P.CustomerID, YEAR(P.CreateDate) as createYear
 
Share this answer
 
Comments
Jamie888 18-Jun-14 5:49am    
i have tried it but it is still the same
Jamie888 18-Jun-14 5:53am    
but if i change it to CustomerID instead of createYear, it works fine but the output is not what i desired.
Sprint89 18-Jun-14 6:10am    
Do you have a field in either the CRF_Project table or the CustomerList table that is called CreateYear? What happens if you use Create_Year?
Jamie888 18-Jun-14 20:40pm    
yes i have the field CreateYear
You can't use an existing field name as an alias:

SQL
SELECT P.DocStatus,C.CustomerName,P.CustomerID, YEAR(CreateDate) as createYear


needs to be

SQL
SELECT P.DocStatus,C.CustomerName,P.CustomerID, YEAR(CreateDate) as Create_Year 


or something similar. Also, it looks like you are using a case-insensitive version of SQL (that isn't a criticism, just information :) )
 
Share this answer
 
v3

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