Here is a function that returns a delimited String as a set of rows
set @string = 'A,B,C,D,E,F'
select * from tbl_test
where tbl_test.code in (select r from ftDelimitedAsTable(',',@string )
--/*----------------------------------------------------------------
Create FUNCTION [dbo].[ftDelimitedAsTable](@dlm char, @string varchar(8000))
RETURNS
--------------------------------------------------------------------------*/
/*------------------------------------------------------------------------
declare @dlm char, @string varchar(1000)
set @dlm=','; set @string='t1,t2,t3';
-- tHIS FUNCION RETUNRS IN THE ASCENDING ORDER
-- 19TH Apr 06
------------------------------------------------------------------------*/
--declare
@table_var TABLE
(id int identity(1,1),
r varchar(1000)
)
AS
BEGIN
-- a.p --
--Modified 18th Nov. 04
declare @n int,@i int
set @n=dbo.fnCountChars(@dlm,@string)+1
SET @I =1
while @I <= @N
begin
--print '@i='+convert(varchar,@i)+ ' AND INSERTING'
insert @table_var
select dbo.fsDelimitedString(@dlm,@string,@i)
set @I= @I+1
end
--PRINT '*************** ALL DONE'
if @n =1 insert @TABLE_VAR VALUES(@STRING)
--select * from @table_var
delete from @table_var where r=''
return
END
USE [QuickPickDBStaging]
GO
/****** Object: UserDefinedFunction [dbo].[fsDelimitedString] Script Date: 02/22/2010 12:31:37 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create function [dbo].[fsDelimitedString](
@DelimiterStr varchar(100)
,@str varchar(4000)
,@pos int=1)
returns varchar(4000)
as
/*
AP -- Dec 2003
Declare @DelimiterStr varchar(4000),@str varchar(4000) ,@pos int
set @delimiterStr = '-'
set @pos=10
set @str ='wd-1-22-333-4444-55555-666666-q-9'
*/
Begin
declare @rx varchar(4000)
set @rx=''; set @pos=@pos-1
IF DBO.fnCountChars(@DelimiterStr,@str) > 0
Begin
if dbo.fnCountChars(@delimiterStr,@str) < @pos
begin
set @rx= null
goto nulls
end
declare @i1 int,@tPos int,@ix int
set @ix=1
set @tPos=0
while @tpos <> @pos
Begin
set @ix=charindex(@DelimiterStr,@str,@ix+1)
if @ix > 0 set @tpos=@tpos+1
end
set @i1= charindex(@DelimiterStr,@str,@ix+1)
if @i1=0
set @rx=substring(@str,@ix+1,len(@str)-@ix)
else
begin
if @ix=1
set @rx=substring(@str,@ix,@i1-@ix)
else
set @rx= substring(@str, @ix+1,@i1-@ix-1)
end
-- 'print 'ix='+convert(varchar,@ix)+' @i1='+convert(varchar,@i1)+' @rx='+@rx
RETURN @RX
end
nulls:
RETURN @rx
end