Click here to Skip to main content
15,898,942 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to use optional statements in the where clause of a stored procedure. SQL Server does not like the first Case statement with red line at closing parenthesis and equal sign. Also red line in second and third Case statement at alias values for fields. The code so far is...

SQL
SELECT c.[Contract], f.Area, dc.DeliverableCategory, d.DueDate, d.DueDateAdjusted, d.CompletedDate, d.PercentComplete, d.Comments

FROM tblDeliverables d LEFT JOIN
    CommonData.dbo.tblContracts c on c.ConID = d.Contract LEFT JOIN
    tblFunctionalAreas f ON f.FunID = d.FunID LEFT JOIN
    tblDeliverableCategories dc ON dc.DelCatID = d.DelCatID LEFT JOIN
    tblEmployeesResponsible e ON e.DelCatID = d.DelCatID

WHERE d.DueDate >= @Start AND d.DueDate <= @End AND
    CASE WHEN @ConID IS NOT NULL THEN (d.[Contract] = @ConID)
         WHEN @FunID IS NOT NULL THEN (d.FunID = @FunID)
         WHEN @EmpID IS NOT NULL THEN (e.EmpID = @EmpID) END
Posted
Updated 4-Aug-14 10:52am
v4
Comments
PIEBALDconsult 4-Aug-14 16:54pm    
In my experience, CASEs are unable to result in a boolean.
So try having them produce a 0 or 1 and test for it.
WHERE CASE something THEN 1 ELSE 0 END = 1
Jörgen Andersson 4-Aug-14 17:07pm    
You should make that an answer instead of a comment.
PIEBALDconsult 4-Aug-14 17:16pm    
I don't yet know whether or not it's the answer. :D

1 solution

Hi,

Try this...

SQL
SELECT c.[Contract], f.Area, dc.DeliverableCategory, d.DueDate, d.DueDateAdjusted, d.CompletedDate, d.PercentComplete, d.Comments
 
	FROM tblDeliverables d LEFT JOIN
		CommonData.dbo.tblContracts c on c.ConID = d.Contract LEFT JOIN
		tblFunctionalAreas f ON f.FunID = d.FunID LEFT JOIN
		tblDeliverableCategories dc ON dc.DelCatID = d.DelCatID LEFT JOIN
		tblEmployeesResponsible e ON e.DelCatID = d.DelCatID
 
	WHERE d.DueDate >= @Start AND d.DueDate <= @End 
               AND d.[Contract] = CASE WHEN @ConID IS NOT NULL THEN  @ConID ELSE d.[Contract] END
               AND d.FunID = CASE WHEN @FunID IS NOT NULL THEN  @FunID ELSE d.FunID END
               AND e.EmpID = CASE WHEN @EmpID IS NOT NULL THEN  @EmpID ELSE e.EmpID END



Hope this will help you.


Cheers
 
Share this answer
 

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