8

There are two strings a and b

The a string contains comma. I would like to split the a string by comma, then go through every element .

IF the b string contains any element which split by comma will return 0

(e.g: a = "4,6,8" ; b = "R3799514" because the b string contains 4 so return 0)

How to achieve this with a stored procedure? Thanks in advance!

I have seen a split function:

CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))     
returns @temptable TABLE (items varchar(8000))     
as     
begin     
declare @idx int     
declare @slice varchar(8000)     

select @idx = 1     
    if len(@String)<1 or @String is null  return     

while @idx!= 0     
begin     
    set @idx = charindex(@Delimiter,@String)     
    if @idx!=0     
        set @slice = left(@String,@idx - 1)     
    else     
        set @slice = @String     

    if(len(@slice)>0)
        insert into @temptable(Items) values(@slice)     

    set @String = right(@String,len(@String) - @idx)     
    if len(@String) = 0 break     
end 
return     
end

select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
user441222
  • 2,001
  • 7
  • 27
  • 41
  • You should normalize db first. http://databases.about.com/od/specificproducts/a/normalization.htm – Gregor Primar Oct 21 '12 at 16:18
  • 2
    Better split functions: http://www.sqlperformance.com/2012/07/t-sql-queries/split-strings and http://www.sqlperformance.com/2012/08/t-sql-queries/splitting-strings-now-with-less-t-sql – Aaron Bertrand Oct 21 '12 at 16:51

1 Answers1

7

Following will work -

DECLARE @A VARCHAR (100)= '4,5,6'
DECLARE @B VARCHAR (100)= 'RXXXXXX'
DECLARE @RETURN_VALUE BIT = 1 --DEFAULT 1


SELECT items
INTO #STRINGS 
FROM dbo.split(@A,',')

IF EXISTS(SELECT 1 FROM #STRINGS S WHERE CHARINDEX(items, @B) > 0)
SET @RETURN_VALUE = 0

PRINT @RETURN_VALUE

DROP TABLE #STRINGS

You can also use CONTAINS instead of CHARINDEX -

IF EXISTS(SELECT 1 FROM #STRINGS S WHERE CONTAINS(items, @B))
SET @RETURN_VALUE = 0
Parag Meshram
  • 8,281
  • 10
  • 52
  • 88