表中A字段内容如下:
AAAAA,BBBBBBBBB,CCCCC,DDDD,EEEE
在SQL 2000中如何找到第3个逗号的索引.
不能用游标,

解决方案 »

  1.   

    declare @str varchar(100)
    set @str='AAAAA,BBBBBBBBB,CCCCC,DDDD,EEEE'select charindex(',',@str,charindex(',',@str,charindex(',',@str)+1)+1)
      

  2.   

    -- ================================================
    -- Template generated from Template Explorer using:
    -- Create Scalar Function (New Menu).SQL
    --
    -- Use the Specify Values for Template Parameters 
    -- command (Ctrl-Shift-M) to fill in the parameter 
    -- values below.
    --
    -- This block of comments will not be included in
    -- the definition of the function.
    -- ================================================
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    -- Author: Name
    -- Create date: 
    -- Description:
    -- =============================================
    CREATE FUNCTION GetPatternIndex 
    (
    -- Add the parameters for the function here
    @Pattern nvarchar(100),
    @Expression nvarchar(100),
    @PatternIndex int
    )
    RETURNS int
    AS
    BEGIN
    -- Declare the return variable here
    DECLARE @Result int -- Add the T-SQL statements to compute the return value here
    declare @i int
    declare @j int
    set @i = @PatternIndex
    set @j = 0

    while @i > 0
    begin
    select @j = Charindex(@Pattern, @Expression, @j + 1)
    set @i = @i - 1
    end set @Result = @j
    -- Return the result of the function
    RETURN @ResultEND
    GO
      

  3.   

    用法:select dbo.GetPatternIndex(',', 'AAAAA,BBBBBBBBB,CCCCC,DDDD,EEEE', 3)没有除bug,所以@PatternIndex如果大于Pattern在Expression已经出现的次数,返回的是最后一次出现的位置。
      

  4.   

    进阶下
    --返回第N个字符前的字符(不含那个字符)
    select left('AAAAA,BBBBBBBBB,CCCCC,DDDD,EEEE',dbo.GetPatternIndex(',','AAAAA,BBBBBBBBB,CCCCC,DDDD,EEEE', 3)-1)--返回第N个字符后的字符(不含那个字符)
    select Right('AAAAA,BBBBBBBBB,CCCCC,DDDD,EEEE',len('AAAAA,BBBBBBBBB,CCCCC,DDDD,EEEE')-dbo.GetPatternIndex(',', 'AAAAA,BBBBBBBBB,CCCCC,DDDD,EEEE', 3))