Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

SQL Server Remove some specific characters from string

SQL Server: I would like to create a function that removes specific characters from a string, based on parameters.

  • parameter1 is original string
  • parameter2 is characters want to removed from original string

For example :

call MyRemoveFunc('32.87.65.54.89', '87.65' ) -- this will return '32.54.89'
call MyRemoveFunc('11.23.45', '23' ) -- this will return '11.45'
call MyRemoveFunc('14.99.16.84', '84.14' ) -- this will return '99.16'
call MyRemoveFunc('11.23.45.65.31.90', '23' ) -- this will return 11.45.65.31.90

call MyRemoveFunc('34.35.36', '35' ) -- this will return 34.36

call MyRemoveFunc('34.35.36.76.44.22', '35' ) -- this will return 34.36.76.44.22

call MyRemoveFunc('34', '34' ) -- this will return blank

call MyRemoveFunc('45.23.11', '45.11' ) -- this will return 23

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is one way using Recursive CTE and Split string function

;WITH data
     AS (SELECT org_string,
                replace_with,
                cs.Item,
                cs.ItemNumber
         FROM   (VALUES ('32.87.65.54.89','87.65' ),
                        ('11.23.45','23' ),
                        ('14.99.16.84','84.14' ),
                        ('11.23.45.65.31.90','23' ),
                        ('34.35.36','35' ),
                        ('34.35.36.76.44.22','35' ),
                        ('34','34' ),
                        ('45.23.11','45.11')) tc (org_string, replace_with)
                CROSS apply [Delimitedsplit8k](replace_with, '.') cs),
     cte
     AS (SELECT org_string,
                replace_with,
                Item,
                Replace('.' + org_string, + '.' + Item, '') AS result,
                ItemNumber
         FROM   data
         WHERE  ItemNumber = 1
         UNION ALL
         SELECT d.org_string,
                d.replace_with,
                d.Item,
                CASE
                  WHEN LEFT(Replace('.' + result, '.' + d.Item, ''), 1) = '.' THEN Stuff(Replace('.' + result, '.' + d.Item, ''), 1, 1, '')
                  ELSE Replace('.' + result, '.' + d.Item, '')
                END,
                d.ItemNumber
         FROM   cte c
                JOIN data d
                  ON c.org_string = d.org_string
                     AND d.ItemNumber = c.ItemNumber + 1)
SELECT TOP 1 WITH ties org_string,
                       replace_with,
                       result = Isnull(Stuff(result, 1, 1, ''), '')
FROM   cte
ORDER  BY Row_number()OVER(partition BY org_string ORDER BY ItemNumber DESC) 

Result :

╔═══════════════════╦══════════════╦════════════════╗
║    org_string     ║ replace_with ║     result     ║
╠═══════════════════╬══════════════╬════════════════╣
║ 11.23.45          ║ 23           ║ 11.45          ║
║ 11.23.45.65.31.90 ║ 23           ║ 11.45.65.31.90 ║
║ 14.99.16.84       ║ 84.14        ║ 99.16          ║
║ 34                ║ 34           ║                ║
║ 34.35.36          ║ 35           ║ 34.36          ║
║ 34.35.36.76.44.22 ║ 35           ║ 34.36.76.44.22 ║
║ 45.23.11          ║ 45.11        ║ 23             ║
║ 32.87.65.54.89    ║ 87.65        ║ 32.54.89       ║
╚═══════════════════╩══════════════╩════════════════╝

The above code can be converted to a user defined function. I will suggest to create Inline Table valued function instead of Scalar function if you have more records.

Split string Function code referred from http://www.sqlservercentral.com/articles/Tally+Table/72993/

 CREATE FUNCTION [dbo].[DelimitedSplit8K]

        (@pString VARCHAR(8000), @pDelimiter CHAR(1))
RETURNS TABLE WITH SCHEMABINDING AS
 RETURN
--===== "Inline" CTE Driven "Tally Table" produces values from 0 up to 10,000...
     -- enough to cover NVARCHAR(4000)
  WITH E1(N) AS (
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
                 SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
                ),                          --10E+1 or 10 rows
       E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
       E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
 cteTally(N) AS (--==== This provides the "base" CTE and limits the number of rows right up front
                     -- for both a performance gain and prevention of accidental "overruns"
                 SELECT TOP (ISNULL(DATALENGTH(@pString),0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
                ),
cteStart(N1) AS (--==== This returns N+1 (starting position of each "element" just once for each delimiter)
                 SELECT 1 UNION ALL
                 SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString,t.N,1) = @pDelimiter
                ),
cteLen(N1,L1) AS(--==== Return start and length (for use in substring)
                 SELECT s.N1,
                        ISNULL(NULLIF(CHARINDEX(@pDelimiter,@pString,s.N1),0)-s.N1,8000)
                   FROM cteStart s
                )
--===== Do the actual split. The ISNULL/NULLIF combo handles the length for the final element when no delimiter is found.
 SELECT ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
        Item       = SUBSTRING(@pString, l.N1, l.L1)
   FROM cteLen l
;
GO

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...