Use regular expressions to replace strings and Server Regular Expressions in SQL server
Create a regular expression replacement function and use the OLE object. The following is the function code:
[SQL]View plain copy
- -- If yes, delete the original function.
- IF OBJECT_ID (N 'dbo. RegexReplace ') IS NOT NULL
- Drop function dbo. RegexReplace
- GO
- -- Start to create a regular expression replacement function
- Create function dbo. RegexReplace
- (
- @ String VARCHAR (MAX), -- replaced string
- @ Pattern VARCHAR (255), -- replace Template
- @ Replacestr VARCHAR (255), -- replaced string
- @ IgnoreCase INT = 0 -- 0 case sensitive 1 case insensitive
- )
- Returns varchar (8000)
- AS
- BEGIN
- DECLARE @ objRegex INT, @ retstr VARCHAR (8000)
- -- Create an object
- EXEC sp_OACreate 'vbscript. RegExp ', @ objRegex OUT
- -- Set attributes
- EXEC sp_OASetProperty @ objRegex, 'pattern', @ Pattern
- EXEC sp_OASetProperty @ objRegex, 'ignorecase', @ IgnoreCase
- EXEC sp_OASetProperty @ objRegex, 'global', 1
- -- Execute
- EXEC sp_OAMethod @ objRegex, 'replace ', @ retstr OUT, @ string, @ replacestr
- -- Release
- EXECUTE sp_OADestroy @ objRegex
- RETURN @ retstr
- END
- GO
- -- Set Ole Automation Procedures to 1 to ensure normal operation.
- EXEC sp_configure 'show advanced options', 1
- RECONFIGURE WITH OVERRIDE
- EXEC sp_configure 'ole Automation Procedures ', 1
- RECONFIGURE WITH OVERRIDE
Copy the preceding code and run it in SQL.
[SQL]View plain copy
- -- 2. Rename
- SELECT dbo. regexReplace ('John Smith ',' ([a-z] +) \ s ([a-z] +) ',' $2, $ 1', 1)
- /*
- --------------------------------------
- Smith, John
- */