使用tsql返回字符串中第n个元素的索引

时间:2011-02-07 13:15:47

标签: sql-server-2005 tsql

如何在SQL Server中返回string中第n个元素的索引。例如,我有字符串: a,b,c,d,e 现在我希望在第三次昏迷之前接收所有元素,所以 a,b,c 。为此,我需要有第三个昏迷的索引。 Charindex不适合这里,因为我不能传递昏迷数,我想要索引。有没有可以做到的内置功能?

更新,@ Andriy M。

嘿,你指出我的链接也很有用。下面我修改了显示的sql以获得我想要的东西:

CREATE FUNCTION [dbo].[nthindexsub](@String varchar(8000), @Delimiter char(1), @DelimitersCount int)       
 returns varchar(8000)
 as       
 begin       
     declare @Substring varchar(8000)
     declare @temptable TABLE (itemindex int identity(1,1), items varchar(8000))
     declare @idx int       
     declare @slice varchar(8000)     

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

     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

     select @Substring = COALESCE(@Substring + ',', '') + items from @temptable where itemindex <= @DelimitersCount  
     return @Substring;
 end

用法:

select dbo.nthindexsub('a,b,c,d,e', ',', 3)

结果是: a,b,c

3 个答案:

答案 0 :(得分:2)

我不确定你为什么只想索引?为什么不将它们分成行,使用行更快更好。这是一个简单的TSQL拆分示例:

DECLARE @List varchar(500)
       ,@SplitOn char(1)
SELECT @List='aaa,bb,c,dd,eeee'
      ,@SplitOn=','
;WITH NumbersCTE AS
(
    SELECT 1 AS Number
    UNION ALL
    SELECT Number+1
        FROM NumbersCTE
        WHERE Number<LEN(@List)
)
, AllSplit AS
(
    SELECT
        ROW_NUMBER() OVER(ORDER BY number) AS RowNumber
            ,LTRIM(RTRIM(SUBSTRING(ListValue, number+1, CHARINDEX(@SplitOn, ListValue, number+1)-number - 1))) AS ListValue
        FROM (
                 SELECT @SplitOn + @List + @SplitOn AS ListValue
             ) AS InnerQuery
            INNER JOIN NumbersCTE n ON n.Number < LEN(InnerQuery.ListValue)
        WHERE SUBSTRING(ListValue, number, 1) = @SplitOn
)
SELECT
    ListValue
    FROM AllSplit
    WHERE RowNumber<=3

输出

ListValue
----------------
aaa
bb
c

在SQL Server 2005中有很多方法可以拆分字符串。本文涵盖几乎所有方法的PRO和CON:

"Arrays and Lists in SQL Server 2005 and Beyond, When Table Value Parameters Do Not Cut it" by Erland Sommarskog

您需要创建拆分功能。这就是如何使用拆分功能:

SELECT
    *
    FROM YourTable                               y
    INNER JOIN dbo.yourSplitFunction(@Parameter) s ON y.ID=s.Value

I prefer the number table approach to split a string in TSQL但是有很多方法可以在SQL Server中拆分字符串(在前面的示例中我使用的是CTE),请参阅上一个链接,该链接解释了每个链接的PRO和CON。

要使Numbers Table方法起作用,您需要进行一次性表设置,这将创建一个包含1到10,000行的表Numbers

SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO Numbers
    FROM sys.objects s1
    CROSS JOIN sys.objects s2
ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)

设置Numbers表后,创建此拆分功能:

CREATE FUNCTION [dbo].[FN_ListToTable]
(
     @SplitOn  char(1)      --REQUIRED, the character to split the @List string on
    ,@List     varchar(8000)--REQUIRED, the list to split apart
)
RETURNS TABLE
AS
RETURN 
(

    ----------------
    --SINGLE QUERY-- --this will not return empty rows
    ----------------
    SELECT
        ListValue
        FROM (SELECT
                  LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
                  FROM (
                           SELECT @SplitOn + @List + @SplitOn AS List2
                       ) AS dt
                      INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
                  WHERE SUBSTRING(List2, number, 1) = @SplitOn
             ) dt2
        WHERE ListValue IS NOT NULL AND ListValue!=''

);
GO 

您现在可以轻松地将CSV字符串拆分为表格并加入其中:

select * from dbo.FN_ListToTable(',','1,2,3,,,4,5,6777,,,')

输出:

ListValue
-----------------------
1
2
3
4
5
6777

(6 row(s) affected)

您可以像这样使用CSV字符串,而不是必需的临时表:

SELECT 
    y.* 
    FROM YourTable  y
        INNER JOIN dbo.FN_ListToTable(',',@MyList) x ON y.pk=x.ListValue
    Where y.aaa='5'

答案 1 :(得分:1)

可以在TSQL中执行,但是 TSQL不擅长(或设计用于)字符串操作,因此如果经常调用它可能会很慢。

最好创建CLR Stored Procedure

答案 2 :(得分:0)

如果您只想要前三个元素,请尝试嵌套CHARINDEX:

DECLARE @YourTable table (csv varchar(50))
INSERT @YourTable VALUES ('aaa,bb,c,dd,eeee')
INSERT @YourTable VALUES ('aaa,bb,c,dd')
INSERT @YourTable VALUES ('aaa,bb,c')
INSERT @YourTable VALUES ('aaa,bb')
INSERT @YourTable VALUES ('aaa')
INSERT @YourTable VALUES (null)

SELECT 
    csv
        ,CHARINDEX(',',csv+',',CHARINDEX(',',csv+',',CHARINDEX(',',csv+',',0)+1)+1) AS ThirdComma
    FROM @YourTable
    WHERE CHARINDEX(',',csv,0)>0 
        AND CHARINDEX(',',csv+',',CHARINDEX(',',csv+',',CHARINDEX(',',csv+',',0)+1)+1)>0

输出:

csv                                                
-------------------------------------------------- -----------
aaa,bb,c,dd,eeee                                   9
aaa,bb,c,dd                                        9
aaa,bb,c                                           9

这将只返回有三个元素的行。如果你想要它有一个,两个和/或三个,试试这个:

DECLARE @YourTable table (csv varchar(50))
INSERT @YourTable VALUES ('aaa,bb,c,dd,eeee')
INSERT @YourTable VALUES ('aaa,bb,c,dd')
INSERT @YourTable VALUES ('aaa,bb,c')
INSERT @YourTable VALUES ('aaa,bb')
INSERT @YourTable VALUES ('aaa')
INSERT @YourTable VALUES (null)

;WITH FindThird AS
(
    SELECT csv, CHARINDEX(',',csv+',',CHARINDEX(',',csv+',',CHARINDEX(',',csv+',',0)+1)+1) AS ThirdComma
    FROM @YourTable
)
SELECT 
    csv
        ,CASE 
             WHEN ThirdComma IS NULL OR ThirdComma=0 THEN LEN(csv)+1
             ELSE ThirdComma
         END AS ThirdComma
    FROM FindThird

输出:

csv                 ThirdComma
------------------- -----------
aaa,bb,c,dd,eeee    9
aaa,bb,c,dd         9
aaa,bb,c            9
aaa,bb              7
aaa                 4
NULL                NULL