Click here to Skip to main content
15,892,575 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Can a list of records be filtered using a comma delimited variable with the TSQL IN operator?

like

SQL
declare @val nvarchar(max)
set @val=  'E1+E2+E3'
set @val=REPLACE(@val,'E','')
set @val=REPLACE(@val,'+',',')
select * from empmas where headcode in(@val)
Posted

You can use the fnsplitter function which is used widely for splitting in t sql... you have to add this function to your database...
SQL
USE [DatabaseName]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create Function [dbo].[fnSplitter] (@IDs Varchar(4000) )  
Returns @Tbl_IDs Table  (ID nvarchar(100) COLLATE SQL_Latin1_General_CP1_CS_AS  )  As  

Begin 
 -- Append comma
 Set @IDs =  @IDs + ',' 
 -- Indexes to keep the position of searching
 Declare @Pos1 Int
 Declare @Pos2 Int
 
 -- Start from first character 
 Set @Pos1=1
 Set @Pos2=1

 While @Pos1<len(@ids)>
 Begin
  Set @Pos1 = CharIndex(',',@IDs,@Pos1)
  Insert @Tbl_IDs Select  Substring(@IDs,@Pos2,@Pos1-@Pos2) 
  -- Go to next non comma character
  Set @Pos2=@Pos1+1
  -- Search from the next charcater
  Set @Pos1 = @Pos1+1
 End 
 Return
End

after adding change your query to
SQL
Declare @val nvarchar(max)
Set @val=  'E1+E2+E3'
Set @val=REPLACE(@val,'E','')
Set @val=REPLACE(@val,'+',',')
Select * from empmas where headcode in(Select ID From fnSplitter(@Val))
 
Share this answer
 
v3
Comments
sanjay acharya 23-Jul-13 3:37am    
Thank you,It solve my problem.
Raja Sekhar S 23-Jul-13 3:46am    
Glad to Help...
yes it can be for example
SQL
select * from Employee where Salary in(5000,8000,15000,40000)
 
Share this answer
 
Comments
sanjay acharya 23-Jul-13 3:00am    
i am taking these value 5000,8000,15000,40000 as @val='5000,8000,15000,40000'

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