之前Nth匹配的SQL文本?

Hel*_*ent 7 sql sql-server substring pattern-matching

使用SQL我想在列中的第3个正斜杠之前返回所有文本

所以

/one/two/three/whatever/testing
Run Code Online (Sandbox Code Playgroud)

会回来:

/one/two/three
Run Code Online (Sandbox Code Playgroud)

在SQL中执行此操作的任何快速而脏的方法(特别是MS SQL 2005+下的MS T-SQL)?

Jam*_*ill 10

既然你说"快速而肮脏",我认为这个非常快速和非常脏的解决方案不会得到一堆下来的选票.下面的SQL使用多个SUBSTRING()函数来查找第三个斜杠:

DECLARE @str VARCHAR(50)
SET @str = '/one/two/three/whatever/testing'
SELECT SUBSTRING(@str, 0, CHARINDEX('/', @str, CHARINDEX('/', @str, CHARINDEX('/', @str, CHARINDEX('/', @str, 0) + 1) + 1) + 1))
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到一个有效的例子.


Sco*_*ard 7

尝试添加该功能

/*
Example:
SELECT dbo.CHARINDEX2('a', 'abbabba', 3)
returns the location of the third occurrence of 'a'
which is 7
*/

CREATE FUNCTION CHARINDEX2
(
    @TargetStr varchar(8000), 
    @SearchedStr varchar(8000), 
    @Occurrence int
)

RETURNS int
AS
BEGIN

    DECLARE @pos INT, @counter INT, @ret INT

    set @pos = CHARINDEX(@TargetStr, @SearchedStr)
    set @counter = 1

    if @Occurrence = 1 set @ret = @pos
    else
    begin

        while (@counter < @Occurrence)
        begin

            select @ret = CHARINDEX(@TargetStr, @SearchedStr, @pos + 1)

            set @counter = @counter + 1

            set @pos = @ret

        end

    end

    RETURN(@ret)

end
Run Code Online (Sandbox Code Playgroud)

然后引用这个函数......

SELECT SUBSTRING('/one/two/three/whatever/testing', 0, dbo.CHARINDEX2('/', '/one/two/three/whatever/testing', 3))
Run Code Online (Sandbox Code Playgroud)

查看这里的文章以获得更好的外观:)