t-sql查找字符串并报告索引

时间:2011-09-11 03:03:50

标签: tsql

给定以下名为@ToSearch的字符串,如何获得与字符串中所有S字符的索引匹配的结果。 例如:

set @ToSearch = 'SQLServer 2008 includes a variety of string and null functions' ;
set @Tofind = 's';

match 1       match 2   match 3       match 4
----------- ----------- ----------- -----------
1              4              23       38

我尝试了这个但是没有像我怀疑那样工作。

SET @ToSearchTemp = 
    SUBSTRING(@ToSearchTemp, CHARINDEX('s',@ToSearchTemp,1), LEN(@ToSearchTemp) );

任何想法如何使用CTE或仅使用查询解决此问题。

2 个答案:

答案 0 :(得分:1)

如果你先create an auxiliary numbers table,那么你可以做

SELECT number 
FROM numbers
WHERE number <= LEN(@ToSearch) AND
SUBSTRING(@ToSearch,number,LEN(@Tofind)) = @Tofind

这将以行格式显示结果。如果您确实需要列格式,则需要PIVOT,但这需要您定义最大结果数或使用动态SQL。

答案 1 :(得分:0)

ALTER PROCEDURE StringSearch 
--(
 @ToSearch VARCHAR(MAX)
,@Tofind   CHAR(1)
--)
AS 

DECLARE @Sentinel INT;
SET @Sentinel =0;
DECLARE @ToSearchTemp VARCHAR(MAX)
SET @ToSearchTemp = @ToSearch
DECLARE @Record int
SET @Record=0;
DECLARE @TestZero int

DECLARE @Matches Table(Match1 int,Id int)
While @Sentinel < LEN(@ToSearch)
    Begin
        INSERT INTO @Matches(Match1,Id)
        VALUES(charindex(@Tofind,@ToSearchTemp)+@Record,@Sentinel+1)
        set @ToSearchTemp = substring(@ToSearchTemp,charindex(@Tofind,@ToSearchTemp)+1,len(@ToSearchTemp))
        print @ToSearchTemp
        SET @TestZero=charindex(@Tofind,@ToSearchTemp)
        if @TestZero=0
        break;
        else
        set @Record =charindex(@Tofind,@ToSearchTemp)+@Record
        SET @Sentinel= @Sentinel +1
    End 

select [1] as Match1, [2] as Match2, [3] as Match3,[4] as Match4

FROM
(
 select top 4  Match1,ID from @Matches
)DataTable
 PIVOT
 (
    sum(Match1)
    For ID
    in ([1],[2],[3],[4])
 ) PivotTable