在SQL Server 2008中按逗号分割字符串

时间:2021-10-05 00:18:01

There are two strings a and b

有两个字符串a和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

如果b字符串包含任何以逗号分割的元素将返回0

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

(例如:a =“4,6,8”; b =“R3799514”因为b字符串包含4所以返回0)

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

如何使用存储过程实现此目的?提前致谢!

I have seen a split function:

我见过一个split函数:

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',',')

1 个解决方案

#1


6  

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 -

您也可以使用CONTAINS而不是CHARINDEX -

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

#1


6  

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 -

您也可以使用CONTAINS而不是CHARINDEX -

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