如何在不丢失数据的情况下更改SQL Server数据库中的列数据类型?
我有 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
您可以使用以下命令轻松完成此操作。任何 0 值都将转换为 0 (BIT = false),其他值将转换为 1 (BIT = true)。
另一种选择是创建一个
BIT
类型的新列,从旧列中填充它,完成后,删除旧列并将新列重命名为旧名称。这样,如果转换过程中出现问题,您可以随时返回,因为您仍然拥有所有数据。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).
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..注意:如果有列的大小,也只需写下大小即可。
Note: if there is a size of columns, just write the size also.
如果是有效的更改。
您可以更改属性。
现在,您可以轻松更改列名称,而无需重新创建表或丢失记录。
If it is a valid change.
you can change the property.
Now you can easily change the column name without recreating the table or losing u r records.
如果你使用T-SQL(MSSQL);你应该尝试这个脚本:
如果你使用 MySQL;你应该尝试这个脚本:
如果你使用 Oracle;你应该尝试这个脚本:
if you use T-SQL(MSSQL); you should try this script:
if you use MySQL; you should try this script:
if you use Oracle; you should try this script:
为什么您认为会丢失数据?只需进入 Management Studio 并更改数据类型即可。如果现有值可以转换为 bool(位),它就会这样做。换句话说,如果在原始字段中“1”映射为 true,“0”映射为 false,那就没问题了。
Why do you think you will lose data? Simply go into Management Studio and change the data type. If the existing value can be converted to bool (bit), it will do that. In other words, if "1" maps to true and "0" maps to false in your original field, you'll be fine.
转到工具-选项-设计器-表和数据库设计器,然后取消选中阻止保存选项
Go to Tool-Option-designers-Table and Database designers and Uncheck Prevent saving option
对我来说,在sql server 2016中,我这样做
*将列Column1重命名为column2
*将列类型从string修改为int:(请确保数据格式正确)
for me , in sql server 2016, I do it like this
*To rename column Column1 to column2
*To modify column Type from string to int:( Please be sure that data are in the correct format)
使用列的检查类型更改列数据类型:
Alter column data type with check type of column :
在紧凑版中,将自动获取日期时间数据类型的大小,即(8),因此无需设置字段的大小并为此操作生成错误...
In compact edition will take size automatically for datetime data type i.e. (8) so no need to set size of field and generate error for this operation...
我可以使用以下查询修改表字段的数据类型:也在 Oracle DB 中,
I can modify the table field's datatype, with these following query: and also in the Oracle DB,
替换数据类型而不丢失数据
Replace datatype without losing data