2012-02-06 5 views
7

Utilizzo di SQL mi piacerebbe tornare tutto il testo prima che la barra 3 ° in una colonnaTesto SQL prima dell'ora N?

così

/one/two/three/whatever/testing 

sarebbero tornati:

/one/two/three 

Qualsiasi modo rapido e sporco per fare questo in SQL (in particolare MS T-SQL con MS SQL 2005+)?

risposta

9

Dal momento che lei ha detto " veloce e sporco ", presumo che questa soluzione molto veloce e molto sporca non riceverà un mucchio di voti bassi. L'SQL di seguito utilizza più SUBSTRING() funzioni per trovare il terzo barra:

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

si può vedere un esempio di lavoro here.

+0

molto bello .. tutto ciò che possiamo fare così funziona anche con questa stringa '/ one/two/three% 20rest/whatever/testing .. grazie. – o365spo

+0

@cyberpine, non sono sicuro di cosa intendi. Per quanto posso dire, funziona correttamente con la stringa nel tuo commento: http://data.stackexchange.com/stackoverflow/query/60986/find-3rd-instance-of –

7

Prova ad aggiungere la funzione

/* 
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 

Poi riferimento alla funzione in quanto tale ...

SELECT SUBSTRING('/one/two/three/whatever/testing', 0, dbo.CHARINDEX2('/', '/one/two/three/whatever/testing', 3)) 

Partenza un articolo here per vedere meglio :)

0
CREATE FUNCTION dbo.CharIndex2 (@expressionToFind VARCHAR(MAX), @expressionToSearch VARCHAR(MAX), @instance INT) 
    RETURNS INT 
BEGIN 
    DECLARE @Position INT 

    DECLARE @i INT = 1 
    WHILE @i <= @instance 
    BEGIN 
     SET @Position = CHARINDEX(@expressionToFind,@expressionToSearch,COALESCE(@Position+1,1)) 
     SET @i += 1 
    END 

    RETURN @Position 
END 
GO