如何在不丢失数据的情况下更改 SQL 数据库中的列数据类型 [英] How to change column datatype in SQL database without losing data

查看:26
本文介绍了如何在不丢失数据的情况下更改 SQL 数据库中的列数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 SQL Server 数据库,我刚刚意识到我可以将其中一列的类型从 int 更改为 bool.

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?

推荐答案

您可以使用以下命令轻松完成此操作.任何值 0 都会变成 0(BIT = false),其他任何值都会变成 1(BIT = true).

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

另一种选择是创建一个 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..

这篇关于如何在不丢失数据的情况下更改 SQL 数据库中的列数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆