51

User-Defined Functions & Collating Sequences Full support for user-defined functions and collating sequences means that in many cases if SQLite doesn't have a feature, you can write it yourself in your favorite .NET language. Writing UDF's and collating sequences has never been easier

I spotted this bit on the C# SQLite ADO.NET provider l found here, and was having problems understanding the documentation on how to implement/use user-defined functions.

Could anyone explain how to, or provide any working examples for this lost newbie?

1 Answer 1

70

Robert Simpson has a great example of a REGEX function you can use in your sqlite queries:

// taken from http://sqlite.phxsoftware.com/forums/p/348/1457.aspx#1457
[SQLiteFunction(Name = "REGEXP", Arguments = 2, FuncType = FunctionType.Scalar)]
class MyRegEx : SQLiteFunction
{
   public override object Invoke(object[] args)
   {
      return System.Text.RegularExpressions.Regex.IsMatch(Convert.ToString(args[1]),Convert.ToString(args[0]));
   }
}

// example SQL:  SELECT * FROM Foo WHERE Foo.Name REGEXP '$bar'
3
  • 7
    For reference, see this answer how to bind it to a SQLiteConnection.
    – metadings
    Commented Oct 2, 2014 at 6:19
  • Your answer is correct. But the example SQL won't use the defined SQLiteFunction but rather the built-in function. One would call SELECT * FROM foo WHERE REGEXP(name, 'mySearchText')
    – Lemmes
    Commented Nov 7, 2023 at 15:29
  • 1
    @Lemmes – that isn't quite true, as the REGEXP operator is equivalent to the function call and thus will invoke the user-supplied function.
    – simonwo
    Commented Jun 5 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.