SQL Server Migrate from float to decimal

hlswsv35  于 2023-03-22  发布在  其他
关注(0)|答案(2)|浏览(145)

Certain tables in our SQL Server have floats in places where it should be decimals for precision. We could make the change in the database, but then our .NET application which still expects a float will crash. Something we have tried is to change the fields in our entities to decimal, but this creates conversion problems (as the database still has floats). Another thing we tried is to use HasConversion in the ModelBuilder with a ValueConverter. This works, but then if we change the database to decimal, this solution will no longer work.

An alternative is to introduce a new computed field which is a decimal based on the float and then let the application use the new field. But we are trying to avoid this solution as it creates a lot of work.

Has anyone solved this problem in an elegant way?

5lhxktic

5lhxktic1#

I'd consider doing this.

  1. Create a view based on your table. Make it an exact replica/pass through values.
  2. Point your application to your new view
  3. Modify your table's columns
  4. Update your application, if desired, to use decimals.
mkshixfv

mkshixfv2#

To avoid a long downtime - and allow time to modify the .NET code, you could do the following:

  1. Rename the original table
  2. Modify original table - changing column from float to decimal
  3. Create a view that converts decimal to float
  4. Add instead of triggers on the view that convert the float to decimal for insert/update and an instead of delete trigger to handle deleting the data.
  5. Create a synonym with the original name - directed to the view

As far as the .NET application code is concerned, the original table still exists with the column defined as float. The instead of triggers take care of the conversion to/from float as needed.

New development can then use the actual table instead of the view once it has been updated and deployed.

You could add a computed column for the float value in the actual table and use the view to output the computed column, with the instead of triggers converting from float to decimal and updating the decimal value.

相关问题