Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008: Bulk Datatype Change

I have an SQL Server 2008 database with many tables. I've been using the now lame datetime datatype and want to use the new and better datetime2. In most places where I have a datetime field, the corresponding column name is Timestamp. Is there anywhere to do a bulk change from datatime to datetime2?

like image 677
Mel Avatar asked Jan 21 '23 11:01

Mel


1 Answers

Run this in Management Studio, copy the result and paste into new Query Window:

select 'ALTER TABLE ' + OBJECT_NAME(o.object_id) + 
    ' ALTER COLUMN ' + c.name + ' DATETIME2 ' +
    CASE WHEN c.is_nullable = 0 THEN 'NOT NULL' ELSE 'NULL' END 
from sys.objects o
inner join sys.columns c on o.object_id = c.object_id
inner join sys.types t on c.system_type_id = t.system_type_id
where o.type='U'
and c.name = 'Timestamp'
and t.name = 'datetime'
order by OBJECT_NAME(o.object_id)
like image 135
devio Avatar answered Jan 31 '23 21:01

devio