-- 表名称
DECLARE @TableName NVARCHAR(128);
-- 字段名称
DECLARE @ColumnName NVARCHAR(128);
-- 当前的精度
DECLARE @CurrentPrecision TINYINT;
DECLARE ColumnCursor CURSOR FOR
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
-- 指定要修改的数据类型
WHERE DATA_TYPE = 'DATETIME2';
OPEN ColumnCursor;
FETCH NEXT FROM ColumnCursor INTO @TableName, @ColumnName;
WHILE @@FETCH_STATUS = 0
BEGIN
-- 查询当前精度为 7 的字段
SELECT @CurrentPrecision = 7
FROM SYS.COLUMNS
WHERE OBJECT_ID = OBJECT_ID(@TableName) AND NAME = @ColumnName;
BEGIN
PRINT 'ALTER TABLE ' + @TableName + ' ALTER COLUMN ' + @ColumnName + ' DATETIME2(0)';
-- 修改数据类型 这里将DATETIME2(7) 修改为了 DATETIME2(0)
EXEC('ALTER TABLE ' + @TableName + ' ALTER COLUMN ' + @ColumnName + ' DATETIME2(0)');
END
FETCH NEXT FROM ColumnCursor INTO @TableName, @ColumnName;
END
CLOSE ColumnCursor;
DEALLOCATE ColumnCursor;
注意:索引会导致 ALTER COLUMN 失败,必要时可以暂时先删除索引,修改完成后重新添加索引。