0

我继承了一个遗留的 VB6 应用程序来维护,而我的 vb6 有点生锈......

我有一个 DAO 表,它有一个类型为 DAO.DataTypeEnum.dbInteger 的字段,需要将其更改为类型 DAO.DataTypeEnum.dbLong。是否有设置这种新数据类型并保留现有值的快捷 vb6 方法,或者我是否需要创建一个临时列来存储数据,然后删除并重新创建具有新数据类型的列,然后手动迁移数据?

4

2 回答 2

2

如果您的数据库引擎支持 ALTER TABLE ALTER COLUMN,Shahkalpesh 的回答很好。如果您使用 Access 数据库引擎(Jet .mdb、ACE .accdb 等),您可以在ANSI-92 查询模式(Jet 4.0 和 Access 2002 及更高版本)下使用 ALTER COLUMN。

在过去,我完全通过代码完成了这样的操作。下面的代码在不使用 ALTER COLUMN 的情况下将字符串字段转换为浮点双精度。它创建一个具有不同名称和正确数据类型的新字段,复制数据,删除原始字段,并将新字段重命名为原始名称。您可以轻松地将其调整为整数到长整数。

  Dim fld As DAO.Field

  ' Cant just change the type of an existing field. '
  ' Instead have to create the new field with a temporary name, '
  ' fill it with the required data, delete the old MyField field '
  ' and then rename the new field. The renaming has to be done '
  ' with DAO - cant do it through SQL '

  ' Add TEMP_MyField field: required double field. Will be renamed later '
  sSQL = "ALTER TABLE MyTable " & _
         "ADD COLUMN TEMP_MyField DOUBLE NOT NULL "
  dbDatabase.Execute sSQL, dbFailOnError

  ' Copy the MyField values to the TEMP_MyField field '
  sSQL = "UPDATE MyTable SET TEMP_MyField = CDbl(MyField)"
  dbDatabase.Execute sSQL, dbFailOnError

  ' Delete the original MyField field (the text field) '
  sSQL = "ALTER TABLE MyTable DROP COLUMN MyField"
  dbDatabase.Execute sSQL, dbFailOnError

  ' Need to refresh the TableDefs to make sure new field shows up '
  dbDatabase.TableDefs.Refresh

  ' Get a reference to the temporary MyField field we just created '
  Set fld = dbDatabase.TableDefs("MyTable").Fields("TEMP_MyField")

  ' Rename it to the final name we want it to have '
  fld.Name = "MyField"
于 2009-07-21T13:07:41.177 回答
1

如果这是一次性工作,您可以打开 Access 数据库并更改数据类型。
对这篇文章添加评论,否则。

编辑:您可以在数据库对象上发出 ALTER 语句

CurrentDb.Execute "ALTER TABLE myTable ALTER Column myIntegerColumn Long"
于 2009-07-20T21:02:27.793 回答