We have a DB with a few hundred tables that have a CHAR “Code” field used for various ressources. This code field is the primary key and foreign key for multiple tables.
We now display this code on mouseover of the ressource in our ASP.NET application and when the code is shorter than the CHAR field length, it displays white spaces. We fix this through RTRIMing (which is often overlooked).
- We’ll only have a few 10s to low 100s of active users so performance impact shouldn’t be that big
- Would there be a way to automatically drop and recreate all PK/FK constraints while converting from CHAR TO VARCHAR? I’ve looked a bit at INFORMATION_SCHEMA and it looks like it would be feasible.
In my experience
charcauses many problems, not only unexpected spaces in the front-end:len(): does it return the length of the string including or excluding spaces?charconsumes more disk space than necessary. Since a primary key is included in every index for its table, this can add up to a non-trivial amount of space.So it’s typically a good idea to refactor from
chartovarchar.Depending on the number of tables you have, this can be quite a lot of work. You’d first have to drop every contraint that references the columns. Then you’d:
After that you would re-add constraints. You will find that it takes a lot of trying to add/remove the constraints in the right order. For example, a
foreign keyrequires auniqueconstraint on the referenced column. So you’d have to drop theforeign keybefore theuniqueconstraint.Right click database -> Tasks -> Generate Scriptswould provide you with a lot of the statements for re-creating the constraints, if not always in the correct order.