Changing the data type of a column
Author: Faiz FaraziThis Script will change datatype except PK and FK columns.
-- =============================
USE database_name
GO
declare @colname nchar(100);
declare @tabname nchar(100);
declare @fromtype nchar(100);
declare @totype nchar(100);
declare @size int;
----------------------------------------------------------------------------------
----Modify this part----------
----According to your need ---------
----To mention size of the @fomtype---
----Mention in the @size not in ------
----@fromtype like varchar(6400)------
----split like @fromtype = 'varchar'--
----@size = 6400 --
----------------------------------------------------------------------------------
set @fromtype = 'varchar' -- only change this (from whidh type you want to change. if it is like varchar(100) discard the (100) )
set @size = 15 -- change this to the @fromtype size, for example if varchar(6400), then @size = 6400
set @totype = 'nvarchar(15)' -- only change this (include the size like int (100) )
declare tab cursor for Select distinct table_name from information_schema.columns
open tab
fetch next from tab into @tabname
while @@FETCH_STATUS = 0
begin
declare col cursor for Select column_name from information_schema.columns where data_type = @fromtype and table_name = @tabname and character_maximum_length >= @size;
open col
fetch next from col into @colname
while @@FETCH_STATUS = 0
begin
print 'Changing '+ltrim(@colname)+' from type '+ltrim(@fromtype)+' to '+ltrim(@totype)
begin try
exec('alter table '+@tabname+' alter column '+@colname+' '+@totype)
end try
begin catch
PRINT 'errno: ' + ltrim(str(error_number()))
PRINT 'errmsg: ' + error_message()
end catch
fetch next from col into @colname
end
close col
deallocate col
fetch next from tab into @tabname
end
close tab
deallocate tab
.




























