Search code examples
sqlsql-serverregexexpression

Regular expressions inside SQL Server


I have stored values in my database that look like 5XXXXXX, where X can be any digit. In other words, I need to match incoming SQL query strings like 5349878.

Does anyone have an idea how to do it?

I have different cases like XXXX7XX for example, so it has to be generic. I don't care about representing the pattern in a different way inside the SQL Server.

I'm working with c# in .NET.


Solution

  • stored value in DB is: 5XXXXXX [where x can be any digit]

    You don't mention data types - if numeric, you'll likely have to use CAST/CONVERT to change the data type to [n]varchar.

    Use:

    WHERE CHARINDEX(column, '5') = 1
      AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
      AND ISNUMERIC(column) = 1
    

    References:

    i have also different cases like XXXX7XX for example, so it has to be generic.

    Use:

    WHERE PATINDEX('%7%', column) = 5
      AND CHARINDEX(column, '.') = 0 --to stop decimals if needed
      AND ISNUMERIC(column) = 1
    

    References:

    Regex Support

    SQL Server 2000+ supports regex, but the catch is you have to create the UDF function in CLR before you have the ability. There are numerous articles providing example code if you google them. Once you have that in place, you can use:

    • 5\d{6} for your first example
    • \d{4}7\d{2} for your second example

    For more info on regular expressions, I highly recommend this website.