2013-01-09 11 views
6

Ho una variabile NVARCHAR lungo in cui ho bisogno di sostituire qualche modello come questo:Come posso creare un MODELLO DI SOSTITUZIONE in SQL?

DECLARE @data NVARCHAR(200) = 'Hello [PAT1] stackoverflow [PAT2] world [PAT3]' 

ho bisogno di sostituire tutti [PAT%] con uno spazio vuoto per assomigliare:

'Hello stackoverflow world' 

Come posso fare questo utilizzando T-SQL in SQL Server 2008?

Stavo cercando in altre domande, e ho trovato solo this, ma non mi aiuta, perché non ho bisogno di preservare la parte originale della stringa.

risposta

10

È possibile utilizzare questa funzione per sostituire il modello. Puoi testarlo con questo SQL-Fiddle demo da testare.

CREATE FUNCTION dbo.PatternReplace 
(
    @InputString VARCHAR(4000), 
    @Pattern VARCHAR(100), 
    @ReplaceText VARCHAR(4000) 
) 
RETURNS VARCHAR(4000) 
AS 
BEGIN 
    DECLARE @Result VARCHAR(4000) SET @Result = '' 
    -- First character in a match 
    DECLARE @First INT 
    -- Next character to start search on 
    DECLARE @Next INT SET @Next = 1 
    -- Length of the total string -- 8001 if @InputString is NULL 
    DECLARE @Len INT SET @Len = COALESCE(LEN(@InputString), 8001) 
    -- End of a pattern 
    DECLARE @EndPattern INT 

    WHILE (@Next <= @Len) 
    BEGIN 
     SET @First = PATINDEX('%' + @Pattern + '%', SUBSTRING(@InputString, @Next, @Len)) 
     IF COALESCE(@First, 0) = 0 --no match - return 
     BEGIN 
     SET @Result = @Result + 
      CASE --return NULL, just like REPLACE, if inputs are NULL 
       WHEN @InputString IS NULL 
        OR @Pattern IS NULL 
        OR @ReplaceText IS NULL THEN NULL 
       ELSE SUBSTRING(@InputString, @Next, @Len) 
      END 
     BREAK 
     END 
     ELSE 
     BEGIN 
     -- Concatenate characters before the match to the result 
     SET @Result = @Result + SUBSTRING(@InputString, @Next, @First - 1) 
     SET @Next = @Next + @First - 1 

     SET @EndPattern = 1 
     -- Find start of end pattern range 
     WHILE PATINDEX(@Pattern, SUBSTRING(@InputString, @Next, @EndPattern)) = 0 
      SET @EndPattern = @EndPattern + 1 
     -- Find end of pattern range 
     WHILE PATINDEX(@Pattern, SUBSTRING(@InputString, @Next, @EndPattern)) > 0 
       AND @Len >= (@Next + @EndPattern - 1) 
      SET @EndPattern = @EndPattern + 1 

     --Either at the end of the pattern or @Next + @EndPattern = @Len 
     SET @Result = @Result + @ReplaceText 
     SET @Next = @Next + @EndPattern - 1 
     END 
    END 
    RETURN(@Result) 
END 

Resource link.

+0

Grazie mille !, per qualche motivo non riesco a vedere, quando uso parentesi [] non funziona, ma li ho modificati con parentesi e funziona. Non conoscevo SQL Fiddle, è fantastico! Grazie anche per questo. – Elwi

+1

vedere [questo] (http://www.sqllion.com/2010/12/pattern-matching-regex-in-t-sql/) spiegazione delle parentesi! Prego! – Nico

Problemi correlati