65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 SQL DMO 更改表列的数据类型

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (3投票s)

2006年6月1日

2分钟阅读

viewsIcon

36613

downloadIcon

262

本文档描述了使用 SQL DMO 自动化数据库维护的某些方面。

引言

本文档描述了使用 SQL DMO 自动化数据库维护的某些方面。

背景

在开发生命周期中,您可能会遇到需要更改某些表列的数据类型的情况。例如,在为您的应用程序启用多语言支持时。在这种情况下,数据类型为 charvarchar text 的列需要更改为它们对应的 Unicode 版本(分别为 ncharnvarchar ntext )。

关注点

如果数据库包含许多表,并且每个表都有许多需要更改数据类型的列,那么这项工作将变得非常繁琐。一种解决方法是自动化此任务。本文试图在一定程度上解决这个问题。本文中给出的示例仅适用于 SQL Server 2000 数据库。

在执行此类任务时,会面临一些挑战:

  • 更改具有默认值/检查约束的列
  • 更改类型为“text”的列
  • 更改使用这些列的存储过程和触发器

Using the Code

具有默认值和检查约束的列不能直接更改。在更改此类列之前,必须先删除默认值和检查约束。

'Dropping the checks and save the corresponding script so that it can be enabled later
For Each objCheck in objTable.Checks
    strScripts(lngIndex) = objCheck.Script
    lngIndex = lngIndex + 1
    objCheck.Remove
Next

在更改列后,将它们恢复回去。

'Restore all the checks after the column is altered
For lngIndex = 0 To lngCount - 1
    objDataBase.ExecuteImmediate strScripts(lngIndex)
Next

类型为 text 的列也不能直接使用 T-SQL alter 语句或 SQL DMO 的 alter 方法在列对象上更改。一种解决方法是引入一个新的临时列。

该技术很简单,包括以下步骤:

  1. 添加一个新的临时列
  2. 将现有内容复制到临时列
  3. 删除旧列
  4. 添加一个与旧列同名的新列,但使用新的数据类型
  5. 将临时列的内容复制到此列
  6. 删除临时列

下面的代码片段演示了这一点

'Add a new temporary column
objDataBase.ExecuteImmediate "ALTER TABLE " & objTable.Name & _
			" ADD " & objColumn.Name & "_ ntext"

'Copy the existing content to the temp column
objDataBase.ExecuteImmediate "UPDATE " & objTable.Name & _
			" SET " & objColumn.Name & "_ = " & objColumn.Name

'Remove the old column
objDataBase.ExecuteImmediate "ALTER TABLE " & objTable.Name & _
			" DROP COLUMN " & objColumn.Name

'Add a new column with the same name as the old one, but with the new data type
objDataBase.ExecuteImmediate "ALTER TABLE " & objTable.Name _
			& " ADD " & objColumn.Name & " ntext"

'Copy the contents of the temp column into this
objDataBase.ExecuteImmediate "UPDATE " & objTable.Name & " SET " _
			& objColumn.Name & " = " & objColumn.Name & "_"

'Remove the temp column
objDataBase.ExecuteImmediate "ALTER TABLE " & objTable.Name & _
			" DROP COLUMN " & objColumn.Name & "_"

更改列的数据类型可能会反过来影响其他区域,例如使用这些列的存储过程/触发器。

SQL DMO 允许将数据库对象脚本化到文件或字符串。可以在该字符串上执行查找和替换,然后运行它以更新数据库对象。

历史

  • 2006 年 6 月 1 日:初始发布
© . All rights reserved.