I have faced the similar issue once , can you check the thread where Lars confirmed me to go with the UDF,as we dont have such functionality build in SQL and I have done it by the way Sergio suggested.
If the answer is not fitting you need, can you elaborate more about your problem please so that I can try. But I am sure this will solve your perpose with minor modification.