Congratulations to all the winners of April 2013, they have won INR 3400 cash and INR 20147 worth prizes !
DotNetFunda.Com Logo
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 54506 |  Welcome, Guest!   Register  Login
 Home > Blogs > SQL Server > Simulation of IN clause using CASE statement ...
Niladri.Biswas

Simulation of IN clause using CASE statement

 Blog author: Niladri.Biswas | Posted on: 6/22/2012 | Category: SQL Server Blogs | Views: 688 | Status: [Member] | Points: 75 | Alert Moderator   


Consider the below
Declare @t table(Val int, name varchar(100))
Insert into @t select 1,'name1' union all select 1, 'name2' union all select 2,'name3'
union all select 3,'name4'

select *
from @t 
where val in (1,2)

The output is as under


Val	name
1	name1
1	name2
2	name3

Now we will use CASE statement to simulate the IN clause as under

declare @type int  = 1

select *
from @t 
where val  = case when @type =1 then 1  end or
	  val  = case when @type =1 then 2  end or
	  val  = case when @type =2 then 3  end

Another way

declare @type int  = 1

select *
from @t  as x
where  case when @type = 1 and x.val in (1,2) then 1
	    when @type = 2 AND x.val in (3) then 1
       else 0   
       end = 1 

Another way

declare @type int  = 1

select *
from @t  as x
where  @type = case when x.val in (1,2) then 1 
		    when x.val in (3) then 2 
	       end 

We will receive the same output.Hope this helps




Best Regards,
Niladri Biswas
Found interesting? Add this to:


Experience:6 year(s)
Home page:http://www.dotnetfunda.com
Member since:Monday, October 25, 2010
Level:Diamond
Status: [Member]
Biography:Lead Engineer at HCL Technologies Ltd., having 6 years of experience in IT field.
I love to explore new technologies and love challenges and try to help others as much as possible not only by coding but also by all possible means.
>> Write Response - Respond to this post and get points

More Blogs

About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/20/2013 10:01:40 AM