I am in the process of slimming down a database that has been using char
/varchar
fields where binary
/varbinary
would be a better choice (given the data represented is byte arrays).
One of the fields I am changing is used in foreign key contraints on a number of other tables.
I cannot drop the current FK constraints, migrate the column to its new type and then simply re-create the FK constraints as the data types would not match.
What approach should I take in migrating this? How would you go about it?
Best Answer
Given the next example:
0- Backup, backup & backup your database.
1- Due you are trying to convert varchar to varbinary and there isn't an explicit conversion you should add new columns to your tables. NOTE: You cannot make it non nullables.
2- Copy current values to the new columns:
3- Drop current constraints:
4- Once you have checked new values are correct, drop actual columns:
5- Rename new columns with old names:
6- Make new columns not nullables:
7- Add constraints again:
8- Check final result:
db<>fiddle here