How can I alter this computed column in SQL Server 2008?
The no-fluff, straight-to-business answer is dropping and recreating the computed column:
Just replace TableName, ComputedCol, and NewExpression. This ensures the computed column is amended without disrupting other components.
Paying heed to data types and constraints
Data types and constraints are critical when redefining a computed column. If your new expression involves data conversions, use CAST or CONVERT to circumvent possible crashes. Also, remember to bear in mind the impact on performance when a computed column is persisted or indexed.
Introducing conditions with CASE statement
Your computed column may need to evaluate conditions, for which, CASE is handy:
It's like a mini "Choose Your Own Adventure" in each row!
Order of columns and safeguarding data
Dropping then adding a computed column leads to it being placed at the end. If you're picky about column order, you might need to recreate the table. But don't fret - the rest of the data is left untouched. It's like a really specific, polite poltergeist!
Running queries one at a time
When tampering with your precious columns, it's best to tread lightly. Running queries sequentially gives you a better handle on any error that might crop up:
It's a safety harness while you're swinging from DROP to ADD.
Benefiting from visual tools
For those more artistically inclined, SQL Server Management Studio offers a diagram feature. It lets you visualize the alterations on your table structure, like a modern day Picasso, but for databases.
Was this article helpful?
