Use SQL to drop a column, if it exists in a table
I recently needed to write a script for a customer to run against their database, to delete a column from a table. I wanted to make sure it would only run if that column existed, especially as the column had originally been created by a script that failed to complete and would now not run because of the column’s existence!
After a little Googling I put two resources together to come up with the following solution and test set-up.
Solution
When running this code a second time it will still run, but there are no changes or errors.
Test Set-up
Run this first to test the above solution.
Resources:
- https://coldfusionblog.wordpress.com/2012/10/11/drop-column-if-exists-in-sql-server/
- http://forums.asp.net/t/1960142.aspx?How+to+check+if+a+column+exist+before+dropping (reply marked as answer)