Sql-server – How to change column datatype in SQL database without losing data

altersql-serversql-server-2008

I have SQL Server database and I just realized that I can change the type of one of the columns from int to bool.

How can I do that without losing the data that is already entered into that table?

Best Solution

You can easily do this using the following command. Any value of 0 will be turned into a 0 (BIT = false), anything else will be turned into 1 (BIT = true).

ALTER TABLE dbo.YourTable
   ALTER COLUMN YourColumnName BIT

The other option would be to create a new column of type BIT, fill it from the old column, and once you're done, drop the old column and rename the new one to the old name. That way, if something during the conversion goes wrong, you can always go back since you still have all the data..