Not that this has anything to do with the error you are receiving, but I think you need to start by getting your code correct(as I noted earlier in this thread). The way you are using the UDF is not right. There is a FAQ on using and creating UDFs: http://www.kixtart.org/forums/ubbthreads.php?ubb=showflat&Number=82017&page=1#Post82017
Please consider the following changes: (I could not test this so its very possible there are bugs)
Please read the faq and look through/test my example. If you don't understand why I did it this way then please ask.
If we can get this correct, we might be able to figure out the other problem as well.