如何更改列的数据类型而不用查询删除列? [英] How to change the data type of a column without dropping the column with query?

查看:34
本文介绍了如何更改列的数据类型而不用查询删除列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一列数据类型为:日期时间.但现在我想将其转换为数据类型 varchar.我可以在不删除列的情况下更改数据类型吗?如果是,那么请解释如何?

I have a column which has a datatype : datetime. But now i want to convert it to datatype varchar. Can i alter the datatype without droppping the column? If yes, then please explain how?

推荐答案

如果 ALTER COLUMN 不起作用.

alter column 失败的情况并不少见,因为它无法进行您想要的转换.在这种情况下,解决方案是创建一个虚拟表 TableName_tmp,使用批量插入命令中的专门转换复制数据,删除原始表,然后将 tmp 表重命名为原始表的名称.您必须删除并重新创建外键约束,为了提高性能,您可能希望在填充 tmp 表后创建键.

It is not unusual for alter column to fail because it cannot make the transformation you desire. In this case, the solution is to create a dummy table TableName_tmp, copy the data over with your specialized transformation in the bulk Insert command, drop the original table, and rename the tmp table to the original table's name. You'll have to drop and recreate the Foreign key constraints and, for performance, you'll probably want to create keys after filling the tmp table.

听起来工作量很大?其实不然.

如果您使用的是 SQL Server,则可以让 SQL Server Management Studio 为您完成工作!

If you are using SQL Server, you can make the SQL Server Management Studio do the work for you!

  • 调出您的表格结构(右键单击表格列并选择修改")
  • 进行所有更改(如果列转换是非法的,只需添加新列 - 稍后您将对其进行修补).
  • 右键单击修改"窗口的背景并选择生成更改脚本".在出现的窗口中,您可以将更改脚本复制到剪贴板.
  • 取消修改(毕竟您需要测试脚本),然后将脚本粘贴到新的查询窗口中.
  • 根据需要进行修改(例如,在从 tmp 表声明中删除字段的同时添加您的转换),您现在拥有进行转换所需的脚本.

这篇关于如何更改列的数据类型而不用查询删除列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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