Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I dont want to use if else for very small purpose which took me to write code again and again in the blocks.
How to write it using AND / OR operator:

SQL
if (@datafor year=0)
select * from abc
else
select * from employee
where dataforyear=@dataforyear
Posted
Updated 2-Sep-14 2:35am
v3

I think you have mentioned two different table names in those two SELECT query. I prefer something like this. Check that article for few more examples.
SQL
DECLARE @dataforyear AS NUMERIC
DECLARE @SQLQuery AS NVARCHAR(500)

SET @dataforyear = 0 
SET @SQLQuery = 'SELECT * FROM employee '

IF (@dataforyear <> 0)
BEGIN
   @SQLQuery = @SQLQuery + ' WHERE dataforyear = ' + @dataforyear
END

EXECUTE sp_executesql @SQLQuery

Building Dynamic SQL In a Stored Procedure[^]
 
Share this answer
 
This should serve your purpose.

SQL
select * 
from employee
where (@dataforyear=0 OR dataforyear=@dataforyear)
 
Share this answer
 
Comments
Torakami 2-Sep-14 9:14am    
do i need to check for null as well ?

something like this
select *
from employee
where ((@dataforyear=0 or @DataForYear is null) OR dataforyear=@dataforyear))
_Asif_ 2-Sep-14 9:29am    
well you can do this

select *
from employee
where (IsNull(@dataforyear,0) = 0 OR dataforyear=@dataforyear)
Torakami 3-Sep-14 0:47am    
yeh , this is much better way .. thanks ...
Torakami 3-Sep-14 5:09am    
Hey Sayed , What i think is here if @datafor year comes 0 it wont check in the condition isnull() .. which is wrong ..
Your requirement is very simple and of course it has no need to use AND/OR also, if you know NULLIF, COALESCE functions in SQL. Your query can be modified as follows.
SQL
SELECT	*
FROM	Employee
WHERE	dataforyear = COALESCE(NULLIF(@dataforyear, 0), dataforyear)

Explanation:
If @dataforyear = 0 then NULLIF(@dataforyear, 0) will become NULL. Then COALESCE(NULLIF(@dataforyear, 0), dataforyear) will be COALESCE(NULL, dataforyear) gives you dataforyear in return.
If @dataforyear <> 0 then NULLIF(@dataforyear, 0) will become @dataforyear. Then COALESCE(NULLIF(@dataforyear, 0), dataforyear) will be COALESCE(@dataforyear, dataforyear) gives you @dataforyear in return.
Have fun with quries.
 
Share this answer
 

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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