RegexReplace in SQL Server

My last post was about SQL Server. Even 10+ years later, I’m continually amazed by features which are daily use features in MySQL and Postgresql which are missing from MS SQL Server.

Regular expression matching and replacing is a severely lacking feature.

Sql Server 2005 introduced a means to write user defined functions in .NET code, so this method is uploaded to a sql server and exposed as a function.

[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString RegexReplace(SqlString input, SqlString pattern, SqlString replacement)
{
    var result = System.Text.RegularExpressions.Regex.Replace(input.Value, pattern.Value, replacement.Value);
    return new SqlString(result);
}

 

Now you can use it in select statements.

SELECT        Name, dbo.RegexReplace(Name, N'(?:\d+-)?\d+PPM’, N”) AS e
FROM            Table2

 

Or use it to update tables

update table2 set name=dbo.RegexReplace(Name, N'(?:\d+-)?\d+PPM’, N”)

 

I have absolutely no idea how any database developer could live without this kind of functionality.

SQL Server Command Line Administration

I don’t have SQL Management Studio installed. Perhaps I should install it, it would make my life easier.

Here are the commands I used to create a new database and add myself to it as administrator. I want to own the database too. I don’t want to have to be sa (root for you mysql folk) just to be able to create tables. I want to delegate the ownership of this database instance (not the whole sql server) to a non-admin user. This is just for me, for dev on my laptop.

C:\>osql -E -S .\SQLEXPRESS -V 2 -Q "create database test2"
C:\>osql -E -S .\SQLEXPRESS -V 2 -Q "use test2;exec sp_changedbowner [theknife\jrwren]"
C:\>osql -E -S .\SQLEXPRESS -V 2 -Q "exec sp_configure ‘clr enabled’, 1"
Configuration option ‘clr enabled’ changed from 0 to 1. Run the RECONFIGURE
statement to install.
C:\>osql -E -S .\SQLEXPRESS -V 2 -Q "reconfigure"

Finding this set of commands was the must frustrating experience that I have had in a VERY long time. It made me long for Postgresql or MySQL.