Click here to Skip to main content
15,908,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, Friends..

I am using stored procedure in which there is an optional parameter @equal and default value is NULL. If user give some value to the parameter SQL query has to be changed. I am trying to use Case in Where clause. but its showing some error.
Help me with proper syntax or with better logic

My requirement is When user doesn't give value for @equal then
FiscalYear<@yr
Else
FiscalYear<=@yr

SQL
Select BankCode,(SUM(Debit)-SUM(Credit)) Amt
	From vwDailyData 
	Where Pname=@ParishName and FiscalYear< (CASE WHEN @equal IS NULL THEN @yr ELSE '='+@yr END) 
	and BankCode<>'Cash'
	Group By BankCode

Error Message
Conversion failed when converting the varchar value '=' to data type int.
Posted
Updated 10-Oct-14 10:31am
v2

You will need to work out the details, but syntax like this may work:
SQL
where case when @equal IS null then @yr else null end > FiscalYear
or case when @equal IS not null then @yr else null end = FiscalYear


You cannot but the operator as part of the case statement.
 
Share this answer
 
SQL
SELECT
	BankCode,
	(SUM(Debit) - SUM(Credit)) Amt
FROM
	vwDailyData
WHERE
	Pname = @ParishName
	AND ((@equal IS NULL
			AND FiscalYear < @yr)
		OR (@equal IS NOT NULL
			AND FiscalYear <= @yr))
	AND BankCode <> 'Cash'
GROUP BY
	BankCode
 
Share this answer
 
You can also use the IF else condition e.g.

IF @equal IS null
Select BankCode,(SUM(Debit)-SUM(Credit)) Amt
	From vwDailyData 
	Where Pname=@ParishName and FiscalYear< @yr
	and BankCode<>'Cash'
	Group By BankCode
ELSE
Select BankCode,(SUM(Debit)-SUM(Credit)) Amt
	From vwDailyData 
	Where Pname=@ParishName and FiscalYear<=@yr
	and BankCode<>'Cash'
	Group By BankCode
 
Share this answer
 
Select BankCode,(SUM(Debit)-SUM(Credit)) Amt
From vwDailyData
Where Pname=@ParishName
and (FiscalYear< (CASE WHEN @equal IS NULL THEN @yr END)
or FiscalYear<= (CASE WHEN @equal IS not NULL THEN @yr END))
 
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