This relates to computed columns and default constraints (and possibly other expressions) in SQL Server 2005 (or above). Both of these use an arbitrary expression to generate a value, e.g. (year+1)
for a computed column representing "next year" (this is obviously a simple and stupid example).
What I'm trying to do: I want to be able to determine whether an existing computed column (or default constraint) in some table matches the intended definition, where the latter is defined in a software-generated schema that was used to create the table. I can get the definition of a computed column using sp_helptext
, and the definition of a default constraint from the sys.default_constraints
catalog view.
What I'm having trouble with: The expressions I get back from the above sources are in a normalized/standard form that doesn't match the form used to create the column/constraint. In the example above, SQL normalizes the expression to ([year]+(1))
. Therefore, a simple string comparison between this form and the original form will not reliably determine whether they are the same.
Solutions I've thought of already:
- Generate the original expressions so that they match SQL's form. This requires knowing the rules SQL uses to generate its form, which are not documented, so it's not a great solution.
- Parse both forms into ASTs and compare those. I already an AST for the original form, but I don't have a parser, and would rather not write one.
- Create a temporary table and add a computed column using the original expression, and then read back the normalized expression. This would be pretty reliable, but it feels dirty, since in theory this comparison should be a read-only operation.
Can anyone think of another good option for handling this? My hope is that maybe someone knows of some debugging/diagnostic tool that will spit back the input expression in normalized/standard form.