Question

When a SQL Server CLR UDT is set to a value, that value (as a string) is internally passed to the Parse() method, which is supposed to return an instance of the UDT set to whatever the passed-in string value translates to according to that type's logic. Fine so far, and works great when the input is fully valid.

However, what should Parse() do if the string representation passed to it cannot be parsed according to the type's defined business rules?

As an example, let's say I have a type which represents a book's ISBN (I said it was just an example). Knowing that ISBNs are either nine digits followed by one check digit, or "978" followed by nine digits followed by one check digit, it is easy to define the business rules for what constitutes a valid ISBN. A business requirement is that only valid ISBNs should ever be handled by the system -- anything invalid should immediately raise an error (and the system was not previously built for this; it used to allow anything unique and non-NULL into the ISBN field, which is now being tightened down). If someone inputs a string that is not a valid ISBN, then what is the appropriate action to take in Parse()?

I tried throwing an ArgumentException but this wreaks havoc with other parts of the database logic and eventually brings the application to a grinding halt because of an unhandled Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. error. It seems there must be a better way than that.

Was it helpful?

Solution

Throwing an ArgumentException seems to be the correct way - see Coding User-Defined Types, and specifically the Parse Validation Example:

[SqlMethod(OnNullCall = false)]
public static Point Parse(SqlString s)
{
    if (s.IsNull)
        return Null;

    // Parse input string to separate out points.
    Point pt = new Point();
    string[] xy = s.Value.Split(",".ToCharArray());
    pt.X = Int32.Parse(xy[0]);
    pt.Y = Int32.Parse(xy[1]);

    // Call ValidatePoint to enforce validation
    // for string conversions.
    if (!pt.ValidatePoint()) 
        throw new ArgumentException("Invalid XY coordinate values.");
    return pt;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top