Skip to main content

Multi-threaded caching mechanism for SQL CLR.

public class UserDefinedFunctions
{
    private static readonly ConcurrentDictionary<string, string> Cache = new ConcurrentDictionary<string, string>();

    [SqlFunction]
    public static SqlString GetFromCache(string key)
    {
        string value;
        if (Cache.TryGetValue(key, out value))
            return new SqlString(value);
        return SqlString.Null;
    }

    [SqlProcedure]
    public static void AddToCache(string key, string value)
    {
        Cache.TryAdd(key, value);
    }

    [SqlProcedure]
    public static void ClearCache()
    {
        Cache.Clear();
    }
}