We take pride in your success. We let our positivity drive us, day in and out. Talk to us at Mindfire to know us more.

Software Technology Tips

Suppose we have a simple query
 
Select * from tblPerson where profession in ('Teacher', 'TL', 'Developer')
 
If in the above query we need to pass the list of professions as parameter to a stored procedure. We obviously cannot pass the parameter string as
 
sProff = "'Teacher', 'TL', 'Developer'";
 
This would give an error for multiple parameters because of the single quotes and if we use the parameter without quotes in the query it wouldn't return the correct result.
For this a splitter function can be used
 
create function dbo.UTILfn_Split(
 @String nvarchar (4000),
 @Delimiter nvarchar (10)
 )
returns @ValueTable table ([Value] nvarchar(4000))
begin
 declare @NextString nvarchar(4000)
 declare @Pos int
 declare @NextPos int
 declare @CommaCheck nvarchar(1)
 
 --Initialize
 set @NextString = ''
 set @CommaCheck = right(@String,1)
 
 --Check for trailing Comma, if not exists, INSERT
 --if (@CommaCheck <> @Delimiter )
 set @String = @String + @Delimiter
 
 --Get position of first Comma
 set @Pos = charindex(@Delimiter,@String)
 set @NextPos = 1
 
 --Loop while there is still a comma in the String of levels
 while (@pos <>  0) 
 begin
  set @NextString = substring(@String,1,@Pos - 1)
 
  insert into @ValueTable ( [Value]) Values (@NextString)
 
  set @String = substring(@String,@pos +1,len(@String))
 
  set @NextPos = @Pos
  set @pos  = charindex(@Delimiter,@String)
 end
 
 return
end
 
This function can be used in the query as
 
declare @sQuery1 as varchar(2000)
declare @Delimiter nvarchar (10)

Set @Delimiter = ''','''
 
SET @sQuery1 = 'Select * from tblPerson where profession in (Select * from UTILfn_Split( ' + @sProff + ',' + @Delimiter + '))'
 
exec (@sQuery1)


Related Tags:

Database

Author: Kavita Asnani

top

Database

Let us Connect!

privacy

copyright (c) Mindfire Solutions 2007-2012. Login