适当的mysql udf

时间:2010-07-17 18:52:27

标签: mysql c

我正在尝试为mysql编写一个自定义的用例定义函数,所以我以http://www.mysqludf.org/index.php中的str_ucwords函数为例来构建我自己的函数。

my_bool str_ucwords_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
    /* make sure user has provided exactly one string argument */
    if (args->arg_count != 1 || args->arg_type[0] != STRING_RESULT || args->args[0] == NULL)
    {
        strcpy(message,"str_ucwords requires one string argument");
        return 1;
    }

    /* str_ucwords() will not be returning null */
    initid->maybe_null=0;

    return 0;
}

char *str_ucwords(UDF_INIT *initid, UDF_ARGS *args,
    char *result, unsigned long *res_length, 
    char *null_value, char *error)
{
    int i;
    int new_word = 0;

    // copy the argument string into result
    strncpy(result, args->args[0], args->lengths[0]);

    *res_length = args->lengths[0];

    // capitalize the first character of each word in the string
    for (i = 0; i < *res_length; i++)
    {
        if (my_isalpha(&my_charset_latin1, result[i]))
        {
            if (!new_word)
            {
                new_word = 1;
                result[i] = my_toupper(&my_charset_latin1, result[i]);
            }
        }
        else
        {
            new_word = 0;
        }
    }

    return result;
}

如果我尝试select str_ucwords("test string");,这样可以正常工作,但如果我尝试从像select str_ucwords(name) from name;这样的数据库中选择一个字段,我什么也没有回复。

如何更改此功能以便我可以从数据库中的字段中提取数据?

我已尝试从init函数中删除args->arg_type[0] != STRING_RESULT

1 个答案:

答案 0 :(得分:2)

问题不在于参数的类型,而是调用NULLstr_ucwords_init(因为在检索任何行之前调用str_ucwords_init)。要让str_ucwords使用字段,您必须通过在initid->maybe_null函数中将_init设置为1并将*null_value设置为1(以及{{1}来支持NULL值当实际参数为空时,在result中为NULL,尽管这可能没有必要。

str_ucwords

lib_mysqludf_str的后续版本应该支持函数中的NULL值而不进行更改,这意味着它们也应该使用表列。

相关问题